[% setvar title Apocalypse 6: Subroutines %]
<div id="archive-notice">
    <h3>This file is part of the Perl 6 Archive</h3>
    <p>To see what is currently happening visit <a href="http://www.perl6.org/">http://www.perl6.org/</a></p>
</div>
<div class='pod'>
<pre>=encoding utf-8</pre>
<a name='TITLE'></a><h1>TITLE</h1>
<p>Apocalypse 6: Subroutines</p>
<a name='AUTHOR'></a><h1>AUTHOR</h1>
<p>Larry Wall &lt;<a href='mailto:larry@wall.org'>larry@wall.org</a>&gt;</p>
<a name='VERSION'></a><h1>VERSION</h1>
<pre>  Maintainer: Larry Wall &lt;<a href='mailto:larry@wall.org'>larry@wall.org</a>&gt;
  Date: 7 Mar 2003
  Last Modified: 25 May 2006
  Number: 6
  Version: 6</pre>
<p>This is the Apocalypse on Subroutines.  In Perl culture the term
&quot;subroutine&quot; conveys the general notion of calling something that
returns control automatically when it's done.  This &quot;something&quot; that
you're calling may go by a more specialized name such as &quot;procedure&quot;,
&quot;function&quot;, &quot;closure&quot;, or &quot;method&quot;.  In Perl 5, all such subroutines
were declared using the keyword <code>sub</code> regardless of their specialty.
For readability, Perl 6 will use alternate keywords to declare special
subroutines, but they're still essentially the same thing underneath.
Insofar as they all behave similarly, this Apocalypse will have
something to say about them.  (And if we also leak a few secrets
about how method calls work, that will make Apocalypse 12 all the
easier--presuming we don't have to un-invent anything between now
and then...)</p>
<p>Here are the RFCs covered in this Apocalypse.  PSA stands for &quot;problem,
solution, acceptance&quot;, my private rating of how this RFC will fit into
Perl 6.  I note that none of the RFCs achieved unreserved acceptance
this time around.  Maybe I'm getting picky in my old age.  Or maybe
I just can't incorporate anything into Perl without &quot;marking&quot; it...</p>
<pre>    RFC   PSA   Title
    ---   ---   -----
     21   abc	Subroutines: Replace C&lt;wantarray&gt; with a generic C&lt;want&gt; function
     23   bcc	Higher order functions
     57   abb	Subroutine prototypes and parameters
     59   bcr	Proposal to utilize C&lt;*&gt; as the prefix to magic subroutines
     75   dcr	structures and interface definitions
    107   adr	lvalue subs should receive the rvalue as an argument
    118   rrr	lvalue subs: parameters, explicit assignment, and wantarray() changes
    128   acc	Subroutines: Extend subroutine contexts to include name parameters and lazy arguments
    132   acr	Subroutines should be able to return an lvalue
    149   adr	Lvalue subroutines: implicit and explicit assignment
    154   bdr	Simple assignment lvalue subs should be on by default
    160   acc	Function-call named parameters (with compiler optimizations)
    168   abb	Built-in functions should be functions
    176   bbb	subroutine / generic entity documentation
    194   acc	Standardise Function Pre- and Post-Handling
    271   abc	Subroutines : Pre- and post- handlers for subroutines
    298   cbc	Make subroutines' prototypes accessible from Perl
    334   abb	Perl should allow specially attributed subs to be called as C functions
    344   acb	Elements of @_ should be read-only by default</pre>
<p>In Apocalypses 1 through 4, I used the RFCs as a springboard for
discussion.  In Apocalypse 5 I was forced by the complexity of the
redesign to switch strategies and present the RFCs after a discussion
of all the issues involved.  That was so well received that I'll try
to follow the same approach with this and subsequent Apocalypses.</p>
<p>But this Apocalypse is not trying to be as radical as the one on
regexes.  Well, okay, it is, and it isn't.   Alright, it <i>is</i> radical,
but you'll like it anyway (we hope).  At least the old way of calling
subroutines still works.  Unlike regexes, Perl subroutines don't have
a lot of historical cruft to get rid of.  In fact, the basic problem
with Perl 5's subroutines is that they're not crufty enough, so the
cruft leaks out into user-defined code instead, by the Conservation
of Cruft Principle.  Perl 6 will let you migrate the cruft out of the
user-defined code and back into the declarations where it belongs.
Then you will think it to be very beautiful cruft indeed (we hope).</p>
<p>Perl 5's subroutines have a number of issues that need to be dealt
with.  First of all, they're just awfully slow, for various reasons:</p>
<ul>
<li><a name='Construction of the @_ array'></a>Construction of the <code>@_</code> array</li>
<li><a name='Needless prepping of potential lvalues'></a>Needless prepping of potential lvalues</li>
<li><a name='General model that forces lots of run-time processing'></a>General model that forces lots of run-time processing</li>
<li><a name='Difficulty of optimization'></a>Difficulty of optimization</li>
<li><a name='Storage of unneeded context'></a>Storage of unneeded context</li>
<li><a name='Lack of tail recursion optimization'></a>Lack of tail recursion optimization</li>
<li><a name='Named params that aren't really'></a>Named params that aren't really</li>
<li><a name='Object model that forces double dispatch in some cases'></a>Object model that forces double dispatch in some cases</li>
</ul>
<p>Quite apart from performance, however, there are a number of
problems with usability:</p>
<ul>
<li><a name='Not easy to detect type errors at compile time'></a>Not easy to detect type errors at compile time</li>
<li><a name='Not possible to specify the signatures of certain built-in functions'></a>Not possible to specify the signatures of certain built-in functions</li>
<li><a name='Not possible to define control structures as subroutines'></a>Not possible to define control structures as subroutines</li>
<li><a name='Not possible to type-check any variadic args other than as a list'></a>Not possible to type-check any variadic args other than as a list</li>
<li><a name='Not possible to have a variadic list providing scalar context to its elements'></a>Not possible to have a variadic list providing scalar context to
its elements</li>
<li><a name='Not possible to have lazy parameters'></a>Not possible to have lazy parameters</li>
<li><a name='Not possible to define immediate subroutines (macros)'></a>Not possible to define immediate subroutines (macros)</li>
<li><a name='Not possible to define subroutines with special syntax'></a>Not possible to define subroutines with special syntax</li>
<li><a name='Not enough contextual information available at run time.'></a>Not enough contextual information available at run time.</li>
<li><a name='Not enough contextual information available at compile time.'></a>Not enough contextual information available at compile time.</li>
</ul>
<p>In general, the consensus is that Perl 5's simple subroutine syntax is
just a little <i>too</i> simple.  Well, okay, it's a <i>lot</i> too simple.
While it's extremely orthogonal to always pass all arguments as a
single variadic array, that mechanism does not always map well onto
the problem space.  So in Perl 6, subroutine syntax has blossomed in
several directions.</p>
<p>But the most important thing to note is that we haven't actually added
a lot of syntax.  We've added some, but most of new capabilities come
in through the generalized trait/property system, and the new type
system.  But in those cases where specialized syntax buys us clarity,
we have not hesitated to add it.  (Er, actually, we hesitated quite
a lot.  Months, in fact.)</p>
<p>One obvious difference is that the <code>sub</code> on closures is now optional,
since every brace-delimited block is now essentially a closure.
You can still put the <code>sub</code> if you like.  But it is only required
if the block would otherwise be construed as a hash value; that is,
if it appears to contain a list of pairs.  You can force any block to
be considered a subroutine with the <code>sub</code> keyword; likewise you can
force any block to be considered a hash value with the <code>hash</code> keyword.
But in general Perl just dwims based on whether the top-level is a
list that happens to have a first argument that is a pair or hash:</p>
<pre>    Block		Meaning
    -----		-------
    { 1 =&gt; 2 }		hash { 1 =&gt; 2 }
    { 1 =&gt; 2, 3 =&gt; 4 }	hash { 1 =&gt; 2, 3 =&gt; 4 }
    { 1 =&gt; 2, 3, 4 }	hash { 1 =&gt; 2, 3 =&gt; 4 }
    { %foo, 1 =&gt; 2 }	hash { %foo.pairs, 1 =&gt; 2 }</pre>
<p>[Update: <code>hash</code> has been demoted to a list operator, actually.]</p>
<p>Anything else that is not a list, or does not start with a pair or
hash, indicates a subroutine:</p>
<pre>    { 1 }		sub { return 1 }
    { 1, 2 }		sub { return 1, 2 }
    { 1, 2, 3 }		sub { return 1, 2, 3 }
    { 1, 2, 3 =&gt; 4 }	sub { return 1, 2, 3 =&gt; 4 }
    { pair 1,2,3,4 }	sub { return 1 =&gt; 2, 3 =&gt; 4 }
    { gethash() }	sub { return gethash() }</pre>
<p>This is a syntactic distinction, not a semantic one.  That last two
examples are taken to be subs despite containing functions returning
pairs or hashes.  Note that it would save no typing to recognize the
<code>pair</code> method specially, since <code>hash</code> automatically does pairing
of non-pairs.  So we distinguish these:</p>
<pre>    { pair 1,2,3,4 }	sub { return 1 =&gt; 2, 3 =&gt; 4 }
    hash { 1,2,3,4 }	hash { 1 =&gt; 2, 3 =&gt; 4 }</pre>
<p>If you're worried about the compiler making bad choices before deciding
whether it's a subroutine or hash, you shouldn't.  The two constructs
really aren't all that far apart.  The <code>hash</code> keyword could in fact
be considered a function that takes as its first argument a closure
returning a hash value list.  So the compiler might just compile the
block as a closure in either case, then do the obvious optimization.</p>
<p>Although we say the <code>sub</code> keyword is now optional on a closure, the
<code>return</code> keyword only works with an explicit <code>sub</code>.  (There are
other ways to return values from a block.)</p>
<p>[Update: This is slightly inaccurate; <code>return</code> works from any <code>Routine</code>.
See below.]</p>
<a name='Subroutine Declarations'></a><h2>Subroutine Declarations</h2>
<p>You may still declare a sub just as you did in Perl 5, in which case
it behaves much like it did in Perl 5.  To wit, the arguments still
come in via the <code>@_</code> array.  When you say:</p>
<pre>    sub foo { print @_ }</pre>
<p>that is just syntactic sugar for this:</p>
<pre>    sub foo (*@_) { print @_ }</pre>
<p>That is, Perl 6 will supply a default parameter signature (the precise
meaning of which will be explained below) that makes the subroutine
behave much as a Perl 5 programmer would expect, with all the arguments
in <code>@_</code>.  It is not exactly the same, however.  You may not modify
the arguments via <code>@_</code> without declaring explicitly that you want
to do so.  So in the rare cases that you want to do that, you'll have
to supply the <code>rw</code> trait (meaning the arguments should be considered
&quot;read-write&quot;):</p>
<pre>    sub swap (*@_ is rw) { @_[0,1] = @_[1,0] };</pre>
<p>The Perl5-to-Perl6 translator will try to catch those cases and add
the parameter signature for you when you want to modify the arguments.
(Note: we will try to be consistent about using &quot;arguments&quot; to mean
the actual values you pass to the function when you call it, and
&quot;parameters&quot; to mean the list of lexical variables declared
as part of the subroutine signature, through which you access the
values that were passed to the subroutine.)</p>
<p>Perl 5 has rudimentary prototypes, but Perl 6 type signatures can be
much more expressive if you want them to be.  The entire declaration
is much more flexible.  Not only can you declare types and names of
individual parameters, you can add various traits to the parameters,
such as <code>rw</code> above.  You can add traits to the subroutine itself,
and declare the return type.  In fact, at some level or other,
the subroutine's signature and return type are also just traits.
You might even consider the body of the subroutine to be a trait.</p>
<p>For those of you who have been following Perl 6 development, you'll
wonder why we're now calling these &quot;traits&quot; rather than &quot;properties&quot;.
They're all really still properties under the hood, but we're trying to
distinguish those properties that are expected to be set on containers
at compile time from those that are expected to be set on values
at run time.  So compile-time properties are now called &quot;traits&quot;.
Basically, if you declare it with <code>is</code>, it's a trait, and if you add
it onto a value with <code>but</code>, it's a property.  The main reason for
making the distinction is to keep the concepts straight in people's
minds, but it also has the nice benefit of telling the optimizer
which properties are subject to change, and which ones aren't.</p>
<p>A given trait may or may not be implemented as a method on the
underlying container object.  You're not supposed to care.</p>
<p>[Update: Actually, they're done as mixins if the container type doesn't
already support the role.  See A12.]</p>
<p>There are actually several syntactic forms of trait:</p>
<pre>    rule trait :w {
	  is &lt;ident&gt;[\( &lt;traitparam&gt; \)]?
	| will &lt;ident&gt; &lt;closure&gt;
	| of &lt;type&gt;
	| returns &lt;type&gt;
    }</pre>
<p>[Update: the <code>:w</code> is no longer needed on a rule.]</p>
<p>(We're specifying the syntax here using Perl 6 regexes.  If you don't
know about those, go back and read Apocalypse 5.)</p>
<p>A <code>&lt;type&gt;</code> is actually allowed to be a junction of types:</p>
<pre>    sub foo returns Int|Str {...}</pre>
<p>The <code>will</code> syntax specifically introduces a closure trait without
requiring the extra parens that <code>is</code> would.  Saying:</p>
<pre>    will flapdoodle { flap() and doodle() }</pre>
<p>is exactly equivalent to:</p>
<pre>    is flapdoodle({ flap() and doodle() })</pre>
<p>but reads a little better.  More typically you'll see traits like:</p>
<pre>    will first { setup() }
    will last { teardown() }</pre>
<p>The final block of a subroutine declaration is the &quot;do&quot; trait.  Saying:</p>
<pre>    sub foo { ... }</pre>
<p>is like saying:</p>
<pre>    sub foo will do { ... }</pre>
<p>Note however that the closure eventually stored under the <code>do</code> trait
may in fact be modified in various ways to reflect argument processing,
exception handling, and such.</p>
<p>We'll discuss the <code>of</code> and <code>returns</code> traits later when we discuss
types.  Back to syntax.</p>
<a name='The sub form'></a><h3>The <code>sub</code> form</h3>
<p>A subroutine can be declared as lexically scoped, package scoped,
or unscoped:</p>
<pre>    rule lexicalsub :w {
	&lt;lexscope&gt; &lt;type&gt;?
	&lt;subintro&gt; &lt;subname&gt; &lt;psignature&gt;?
	&lt;trait&gt;*
	&lt;block&gt;
    }

    rule packagesub :w {
	&lt;subintro&gt; &lt;subname&gt; &lt;psignature&gt;?
	&lt;trait&gt;*
	&lt;block&gt;
    }

    rule anonsub :w {
	&lt;subintro&gt; &lt;psignature&gt;?
	&lt;trait&gt;*
	&lt;block&gt;
    }</pre>
<p>The non-lexically scoped declaration cannot specify a return type
in front.  The return type can only be specified as a trait in that case.</p>
<p>[Update: These days the return type may be specified as part of the
signature after a <code>--&gt;</code>.  It's also possible to use a declarator
in front of a declaration that introduces no name.  And again, the <code>:w</code>
is no longer used in rules.]</p>
<p>As in Perl 5, the difference between a package sub and an anonymous
sub depends on whether you specify the <code>&lt;subname&gt;</code>.  If omitted,
the declaration (which is not really a declaration in that case)
generates and returns a closure.  (Which may not <i>really</i> be a
closure if it doesn't access any external lexicals, but we call them
all closures anyway just in case...)</p>
<p>A lexical subroutine is declared using either <code>my</code> or <code>our</code>:</p>
<pre>    rule lexscope { my | our }</pre>
<p>This list doesn't include <code>temp</code> or <code>let</code> because those are not
declarators of lexical scope but rather operators that initiate
dynamic scoping.  See the section below on Lvalue subroutines for
more about <code>temp</code> and <code>let</code>.</p>
<p>In both lexical and package declarations, the name of the subroutine
is introduced by the keyword <code>sub</code>, or one of its variants:</p>
<pre>    rule subintro { sub | method | submethod | multi | rule | macro }</pre>
<p>A <code>method</code> participates in inheritance and always has an invocant
(object or class).  A <code>submethod</code> has an invocant but does not
participate in inheritance.  It's a sub pretending to be a method
for the current class only.  A <code>multi</code> is a multimethod, that is,
a method that is called like a subroutine or operator, but is
dispatched based on the types of one or more of its arguments.</p>
<p>[Update: These days <code>multi</code> is just a modifier on <code>sub</code> or <code>method</code>, but
if you say <code>multi</code> the <code>sub</code> may be omitted since it's the default.]</p>
<p>Another variant is the regex <code>rule</code>, which is really a special kind
of method; but in actuality rules probably get their own set of parse
rules, since the body of a rule is a regex.  I just put &quot;rule&quot; into
&lt;subintro&gt; as a placeholder of sorts, because I'm lazy.</p>
<p>[Update: Rules are now split up into <code>regex</code>, <code>token</code>, and <code>rule</code>
declarations.  These differ in backtracking policy and whitespace matching.
See S05.]</p>
<p>A <code>macro</code> is a subroutine that is called immediately upon completion
of parsing.  It has a default means of parsing arguments, or it may
be bound to an alternate grammar rule to parse its arguments however
you like.</p>
<p>These syntactic forms correspond the various <code>Routine</code> types in the
<code>Code</code> type hierarchy:</p>
<pre>                                   Code
                        ____________|________________
                       |                             |
                    Routine                        Block
       ________________|_______________            __|___
      |     |       |       |    |     |          |      |
     Sub Method Submethod Multi Rule Macro      Bare Parametric</pre>
<p>The <code>Routine</code>/<code>Block</code> distinction is fairly important, since you
always <code>return</code> out of the current <code>Routine</code>, that is, the current
<code>Sub</code>, <code>Method</code>, <code>Submethod</code>, <code>Multi</code>, <code>Rule</code>, or <code>Macro</code>.  Also,
the <code>&amp;_</code> variable refers to your current <code>Routine</code>.  A <code>Block</code>,
whether <code>Bare</code> or <code>Parametric</code>, is invisible to both of those notions.</p>
<p>(It's not yet clear whether the <code>Bare</code> vs <code>Parametric</code> distinction
is useful.  Some apparently <code>Bare</code> blocks are actually <code>Parametric</code>
if they refer to <code>$_</code> internally, even implicitly.  And a <code>Bare</code>
block is just a <code>Parametric</code> block with a signature of <code>()</code>.
More later.)</p>
<p>[Update: There's no longer a Bare/Parametric distinction.]</p>
<p>A <code>&lt;psignature&gt;</code> is a parenthesized signature:</p>
<pre>    rule psignature :w { \( &lt;signature&gt; \) }</pre>
<p>And there is a variant that doesn't declare names:</p>
<pre>    rule psiglet :w { \( &lt;siglet&gt; \) }</pre>
<p>(We'll discuss &quot;siglets&quot; later in their own section.)</p>
<p>It's possible to declare a subroutine in an lvalue or a signature as if
it were an ordinary variable, in anticipation of binding the symbol to an
actual subroutine later.  Note this only works with an explicit name, since
the whole point of declaring it in the first place is to have a name for it.
On the other hand, the formal subroutine's parameters <i>aren't</i> named, hence
they are specified by a <code>&lt;psiglet&gt;</code> rather than a <code>&lt;psignature&gt;</code>:</p>
<pre>    rule scopedsubvar :w {
	&lt;lexscope&gt; &lt;type&gt;? &amp;&lt;subname&gt; &lt;psiglet&gt;? &lt;trait&gt;*
    }

    rule unscopedsubvar :w {
	&amp;&lt;subname&gt; &lt;psiglet&gt;? &lt;trait&gt;*
    }</pre>
<p>If no <code>&lt;psiglet&gt;</code> is supplied for such a declaration, it just
uses whatever the signature of the bound routine is.  So instead of:</p>
<pre>    my sub foo (*@_) { print @_ }</pre>
<p>you could equivalently say:</p>
<pre>    my &amp;foo ::= sub (*@_) { print @_ };</pre>
<p>(You may recall that <code>::=</code> does binding at compile time.  Then again,
you may not.)</p>
<p>If there is a <code>&lt;psiglet&gt;</code>, however, it must be compatible with
the signature of the routine that is bound to it:</p>
<pre>    my &amp;moo(Cow) ::= sub (Horse $x) { $x.neigh };     # ERROR</pre>
<a name='&quot;Pointy subs&quot;'></a><h3>&quot;Pointy subs&quot;</h3>
<p>&quot;Pointy subs&quot; declare a closure with an unparenthesized signature:</p>
<pre>    rule pointysub :w {
	-\&gt; &lt;signature&gt; &lt;block&gt;
    }</pre>
<p>They may not take traits.</p>
<a name='Bare subs'></a><h3>Bare subs</h3>
<p>A bare block generates a closure:</p>
<pre>    rule baresub :w {
	&lt;block&gt; { .find_placeholders() }
    }</pre>
<p>A bare block declaration does not take traits (externally, anyway), and
if there are any parameters, they must be specified with placeholder
variables.  If no placeholders are used, <code>$_</code> may be treated as
a placeholder variable, provided the surrounding control structure
passes an argument to the the closure.  Otherwise, <code>$_</code> is bound as
an ordinary lexical variable to the outer <code>$_</code>.  (<code>$_</code> is also an
ordinary lexical variable when explicit placeholders are used.)</p>
<p>More on parameters below.  But before we talk about parameters,
we need to talk about types.</p>
<a name='Digression on types'></a><h2>Digression on types</h2>
<p>Well, what are types, anyway?  Though known as a &quot;typeless&quot; language,
Perl actually supports several built-in container types such as scalar,
array, and hash, as well as user-defined, dynamically typed objects
via <code>bless</code>.</p>
<p>Perl 6 will certainly support more types.  These include some low-level
storage types:</p>
<pre>    bit int str num ref bool</pre>
<p>as well as some high-level object types:</p>
<pre>    Bit Int Str Num Ref Bool
    Array Hash Code IO
    Routine Sub Method Submethod Macro Rule
    Block Bare Parametric
    Package Module Class Object Grammar
    List Lazy Eager</pre>
<p>(These lists should not be construed as exhaustive.)  We'll also need
some way of at least hinting at representations to the compiler,
so we may also end up with types like these:</p>
<pre>    int8 int16 int32 int64
    uint8 uint16 uint32 uint64</pre>
<p>Or maybe those are just extra <code>size</code> traits on a declaration
somewhere.  That's not important at this point.</p>
<p>The important thing is that we're adding a generalized type system
to Perl.  Let us begin by admitting that it is the height of madness to
add a type system to a language that is well-loved for being typeless.</p>
<p>But mad or not, there are some good reasons to do just that.
First, it makes it possible to write interfaces to other languages
in Perl.  Second, it gives the optimizer more information to think
about.  Third, it allows the S&amp;M folks to inflict strongly typed
compile-time semantics on each other.  (Which is fine, as long as
they don't inflict those semantics on the rest of us.)  Fourth,
a type system can be viewed as a pattern matching system for
multi-method dispatch.</p>
<p>Which basically boils down to the notion that it's fine for Perl
to have a type system as long as it's optional.  It's just another
area where Perl 6 will try to have its cake and eat it too.</p>
<p>This should not actually come as a surprise to anyone who has been
following the development of Perl 5, since the grammatical slot
for declaring a variable's effective type has been defined for some
time now.  In Perl 5 you can say:</p>
<pre>    my Cat $felix;</pre>
<p>to declare a variable intended to hold a <code>Cat</code> object.  That's nice, as far
as it goes.  Perl 6 will support the same syntax, but we'll have
to push it much further than that if we're to have a type system
that is good enough to specify interfaces to languages like C++
or Java.  In particular, we have to be able to specify the types of
composite objects such as arrays and hashes without resorting to class
definitions, which are rather heavyweight--not to mention opaque.
We need to be able to specify the types of individual function and
method parameters and return values.  Taken collectively, these
parameter types can form the signature of a subroutine, which is one
of the traits of the subroutine.</p>
<p>And of course, all this has to be intuitively obvious to the naive
user.</p>
<p>Yeah, sure, you say.</p>
<p>Well, let's see how far we can get with it.  If the type system is
too klunky for some particular use, people will simply avoid using it.
Which is fine--that's why it's optional.</p>
<p>First, let's clarify one thing that seems to confuse people frequently.
Unlike some languages, Perl makes a distinction between the type of
the variable, and the type of the value.  In Perl 5, this shows up
as the difference between overloading and tying.  You overload the
value, but you tie the variable.  When you say:</p>
<pre>    my Cat $felix;</pre>
<p>you are specifying the type of the <i>value</i> being stored, not the
type of the <i>variable</i> doing the storing.  That is, <code>$felix</code> must
contain a reference to a <code>Cat</code> value, or something that &quot;isa&quot; <code>Cat</code>.
The variable type in this case is just a simple scalar, though that
can be changed by tying the variable to some class implementing the
scalar variable operations.</p>
<p>In Perl 6, the type of the variable is just one of the traits of the
variable, so if you want to do the equivalent of a <code>tie</code> to the <code>Box</code>
class, you say something like:</p>
<pre>    my Cat $felix is Box;</pre>
<p>That declares your intent to store a <code>Cat</code> value into a <code>Box</code>
variable.  (Whether the cat will then dead or alive (or dead|alive)
depends on the definition of the <code>Box</code> class, and whether the <code>Box</code>
object's side effects extend to the <code>Cat</code> value stored in it.)</p>
<p>But by default:</p>
<pre>    my Cat $felix;</pre>
<p>just means something like:</p>
<pre>    my Cat $felix is Scalar;</pre>
<p>Likewise, if you say:</p>
<pre>    my Cat @litter;</pre>
<p>it's like saying:</p>
<pre>    my Cat @litter is Array;</pre>
<p>That is, <code>@litter</code> is an ordinary array of scalar values that happen
to be references to <code>Cat</code>s.  In the abstract, <code>@litter</code> is a function
that maps integers to cats.</p>
<p>Likewise,</p>
<pre>    my Cat %pet;</pre>
<p>is like:</p>
<pre>    my Cat %pet is Hash;</pre>
<p>You can think of the <code>%pet</code> hash as a function that maps cat names
(strings) to cats.  Of course, that's an oversimplification--for both
arrays and hashes, subscripting is not the only operation.  But it's
the fundamental operation, so the declared type of the returned value
reflects the return value of such a subscripted call.</p>
<p>Actually, it's not necessarily the return type.  It's merely a type
that is <i>consistent</i> with the returned type.  It would be better
to declare:</p>
<pre>    my Animal %pet;</pre>
<p>and then you could return a <code>Cat</code> or a <code>Dog</code> or a <code>Sponge</code>, presuming all
those are derived from <code>Animal</code>.  You'd have to generalize it a bit
further if you want to store your pet <code>Rock</code>.  In the limit, you can
just leave the type out.  When you say:</p>
<pre>    my %pet;</pre>
<p>you're really just saying:</p>
<pre>    my Object %pet is Hash;</pre>
<p>...except that you're not.  We have to push it further than that,
because we have to handle more complicated structures as well.
When you say:</p>
<pre>    my Cat @litter is Array;</pre>
<p>it's really shorthand for:</p>
<pre>    my @litter is Array of Cat;</pre>
<p>That is, &quot;<code>Cat</code>&quot; is really a funny parameter that says what kind of
<code>Array</code> you have.  If you like, you could even write it like this:</p>
<pre>    my @litter is Array(returns =&gt; Cat)</pre>
<p>Likewise you might write:</p>
<pre>    my %pet is Hash(keytype =&gt; Str, returns =&gt; Cat)</pre>
<p>and specify the key type of the hash.  The &quot;<code>of</code>&quot; keyword is just
syntactic sugar for specifying the return type of the previous
storage class.  So we could have</p>
<pre>    my %pet is Hash of Array of Array of Hash of Array of Cat;</pre>
<p>which might really mean:</p>
<pre>    my %pet is Hash(keytype =&gt; Str,
		    returns =&gt; Array(
			returns =&gt; Array(
			    returns =&gt; Hash(
				keytype =&gt; Str,
				returns =&gt; Array(
				    returns =&gt; Cat)))))</pre>
<p>or some such.</p>
<p>[Update: Type parameters are now written with square brackets, and
we now distinguish the <code>of</code> property from the <code>returns</code> property.]</p>
<p>I suppose you could also write that as:</p>
<pre>    my Array of Array of Hash of Array of Cat %pet;</pre>
<p>but for linguistic reasons it's probably better to keep the variable
name near the left and put the long, heavy phrases to the right.
(People tend to prefer to say the short parts of their sentences
before the long parts--linguists call this the &quot;end-weight&quot; problem.)
The <code>Hash</code> is implied by the <code>%pet</code>, so you could leave out the &quot;<code>is</code>&quot;
part and just say:</p>
<pre>    my %pet of Array of Array of Hash of Array of Cat;</pre>
<p>Another possibility is:</p>
<pre>    my Cat %pet is Hash of Array of Array of Hash of Array;</pre>
<p>That one reads kinda funny if you leave out the &quot;<code>is Hash</code>&quot;, though.
Nevertheless, it says that we have this funny data structure that
has multiple parameters that you can view as a funny function
returning <code>Cat</code>.  In fact, &quot;<code>returns</code>&quot; is a synonym for &quot;<code>of</code>&quot;.
This is also legal:</p>
<pre>    my @litter returns Cat;</pre>
<p>[Update: Not any more.]</p>
<p>But the &quot;<code>returns</code>&quot; keyword is mostly for use by functions:</p>
<pre>    my Cat sub find_cat($name) {...}</pre>
<p>is the same as:</p>
<pre>    my sub find_cat($name) returns Cat {...}</pre>
<p>This is more important for things like closures that have no &quot;<code>my</code>&quot;
on the front:</p>
<pre>    $closure = sub ($name) returns Cat {...}</pre>
<p>Though for the closure case, it's possible we could define some kind
of non-<code>my</code> article to introduce a type unambiguously:</p>
<pre>    $closure = a Camel sub ($name) {...}
    $closure = an Aardvark sub () {...}</pre>
<p>Presumably &quot;<code>a</code>&quot; or &quot;<code>an</code>&quot; is short for &quot;anonymous&quot;.  Which is more or
less what the indefinite article means in English.</p>
<p>[Update: You can just use <code>my</code> there and leave the name out.]</p>
<p>However, we need <code>returns</code> anyway in cases where the return value
is complicated, so that you'd rather list it later (for end-weight
reasons):</p>
<pre>    my sub next_prisoner() returns (Nationality, Name, Rank, SerialNo) {...}</pre>
<p>Note that the return type is a signature much like the parameter types,
though of course there are no formal parameter names on a return value.
(Though there could be, I suppose.)  We're calling such nameless
signatures &quot;siglets&quot;.</p>
<p>[Update: It turns out that the <code>returns</code> property just constrains
the return type as seen by the routine, and not the return type
seen by the rest of the world.  Use the type prefix or arrow form
to declare a return type that is seen by the rest of the world, and
in particular any type inferencing engine.  We call that the <code>of</code>
type to distinguish it from the <code>where</code> type that is specified by
the <code>returns</code> property.]</p>
<a name='Stub declarations'></a><h2>Stub declarations</h2>
<p>When you declare a subroutine, it can change how the rest of the
current file (or string) is compiled.  So there is some pressure to
put subroutine declarations early.  On the other hand, there are good
reasons for putting subroutine definitions later in the file too,
particularly when you have mutually recursive subroutines.  Beyond
that, the definition might not even be supplied until run time if you
use some kind of autoloading mechanism.  (We'll discuss autoloading
in Apocalypse 10, Packages.)  Perl 5 has long supported the notion of
&quot;forward&quot; declarations or &quot;stubs&quot; via a syntax that looks like this:</p>
<pre>    sub optimal;</pre>
<p>Perl 6 also supports stubbing, but instead you write it like this:</p>
<pre>    sub optimal {...}</pre>
<p>That is, the stub is distinguished not by leaving the body of the
function out, but by supplying a body that explicitly calls the
&quot;<code>...</code>&quot; operator (known affectionately as the &quot;yada, yada, yada&quot;
operator).  This operator emits a warning if you actually try to
execute it.  (It can also be made to pitch an exception.)  There is
no warning for redefining a <code>{...}</code> body.</p>
<p>We're moving away from the semicolon syntax in order to be consistent
with the distinction made by other declarations:</p>
<pre>    package Fee;	# scope extends to end of file
    package Fee { ... }	# scope extends over block

    module Fie;		# scope extends to end of file
    module Fie { ... }	# scope extends over block

    class Foe;		# scope extends to end of file
    class Foe { ... }	# scope extends over block</pre>
<p>To be consistent, a declaration like:</p>
<pre>    sub foo;</pre>
<p>would therefore extend to the end of the file.  But that would be
confusing for historical reasons, so we disallow it instead, and you
have to say:</p>
<pre>    sub foo {...}</pre>
<p>[Update: Perl 6 also allows you to defer declaring your subroutine
till later in the file, but only if the delayed declaration declares
the sub to be parsed consistent with how a list operator would be
parsed.  Basically, any unrecognized &quot;bareword&quot; is assumed to be a
provisional list operator that must be declared by the end of the
current compilation unit.]</p>
<a name='Scope of subroutine names'></a><h2>Scope of subroutine names</h2>
<p>Perl 5 gives subroutine names two scopes.  Perl 6 gives them four.</p>
<a name='Package scoped subs'></a><h3>Package scoped subs</h3>
<p>All named subs in Perl 5 have package scope.  (The body provides a
lexical scope, but we're not talking about that.  We're talking about
where the name of the subroutine is visible from.)  Perl 6 provides
by default a package-scoped name for &quot;unscoped&quot; declarations such
as these:</p>
<pre>          sub fee {...}
       method fie {...}
    submethod foe {...}
        multi foo {...}
        macro sic {...}</pre>
<p>Methods and submethods are ordinarily package scoped, because (just
as in Perl 5) a class's namespace is kept in a package.</p>
<a name='Anonymous subs'></a><h3>Anonymous subs</h3>
<p>It's sort of cheating to call this a subroutine scope, because it's
really more of a non-scope.  Scope is a property of the <i>name</i>
of a subroutine. Since closures and anonymous subs have no name,
they naturally have no intrinsic scope of their own.  Instead, they
rely on the scope of whatever variable contains a reference to them.
The only way to get a lexically scoped subroutine name in Perl 5 was
by indirection:</p>
<pre>    my $subref = sub { dostuff(@_) }
    &amp;$subref(...)</pre>
<p>But that doesn't actually give you a lexically scoped name that is
equivalent to an ordinary subroutine's name.  Hence, Perl 6 also
provides...</p>
<a name='Lexically scoped subs'></a><h3>Lexically scoped subs</h3>
<p>You can declare &quot;scoped&quot; subroutines by explicitly putting a <code>my</code>
or <code>our</code> on the front of the declaration:</p>
<pre>    my sub privatestuff { ... }
    our sub semiprivatestuff { ... }</pre>
<p>Both of these introduce a name into the current lexical scope, though
in the case of <code>our</code> this is just an alias for a package subroutine
of the same name.  (As with other uses of <code>our</code>, you might want
to introduce a lexical alias if your strictness level prohibits
unqualified access to package subroutines.)</p>
<p>You can also declare lexically scoped macros:</p>
<pre>    my macro sic { ... }</pre>
<a name='Global scoped subs'></a><h3>Global scoped subs</h3>
<p>Perl 6 also introduces the notion of completely global variables that
are visible from everywhere they aren't overridden by the current
package or lexical scope.  Such variables are named with a leading <code>*</code>
on the identifier, indicating that the package prefix is a wildcard,
if you will.  Since subroutines are just a funny kind of variable,
you can also have global subs:</p>
<pre>    sub *print (*@list) { $*DEFOUT.print(@list) } }</pre>
<p>In fact, that's more-or-less how some built-in functions like <code>print</code>
could be implemented in Perl 6.  (Methods like <code>$*DEFOUT.print()</code>
are a different story, of course.  They're defined off in a
class somewhere.  (Unless they're multimethods, in which case they
could be defined almost anywhere, because multimethods are always
globally scoped.  (In fact, most built-ins including <code>print</code> will
be multimethods, not subs. (But we're getting ahead of ourselves...))))</p>
<a name='Signatures'></a><h2>Signatures</h2>
<p>One of Perl's strong points has always been the blending of
positional parameters with variadic parameters.</p>
<p>&quot;Variadic&quot; parameters are the ones that <i>vary</i>.  They're the &quot;...And
The Rest&quot; list of values that many functions--like <code>print</code>, <code>map</code>,
and <code>chomp</code>--have at the end of their call.  Whereas positional
parameters generally tell a function <i>how</i> to do its job, variadic
parameters are most often used to pass the arbitrary sequences of
data the function is supposed to do its job on/with/to.</p>
<p>In Perl 5, when you unpack the arguments to a <code>sub</code> like so:</p>
<pre>    my ($a, $b, $c, @rest) = @_;</pre>
<p>you are defining three positional parameters, followed by a variadic
list.  And if you give the sub a prototype of <code>($$$@)</code> it will force the
first three parameters to be evaluated in scalar context, while the
remaining arguments are evaluated in list context.</p>
<p>The big problem with the Perl 5 solution is that the parameter
binding is done at run time, which has run-time costs.  It also
means the metadata is not readily available outside the function body.
We could just as easily have written it in some other form like:</p>
<pre>    my $a = shift;
    my $b = shift;
    my $c = shift;</pre>
<p>and left the rest of the arguments in <code>@_</code>.  Not only is this
difficult for a compiler to analyze, but it's impossible to get the
metadata from a stub declaration; you have to have the body defined
already.</p>
<p>The old approach is very flexible, but the cost to the user is
rather high.</p>
<p>Perl 6 still allows you to access the arguments via <code>@_</code> if you
like, but in general you'll want to hoist the metadata up into
the declaration.  Perl 6 still fully supports the distinction
between positional and variadic data--you just have to declare them
differently.  In general, variadic items must follow positional items
both in declaration and in invocation.</p>
<p>In turn, there are at least three kinds of positional parameters, and
three kinds of variadic parameters.  A declaration for all six kinds
of parameter won't win a beauty contest, but might look like this:</p>
<pre>    method x ($me: $req, ?$opt, +$namedopt, *%named, *@list) {...}</pre>
<p>[Update: that currently looks like this:</p>
<pre>    method x ($me: $req, $opt?, :$namedopt, *%named, *@list) {...}</pre>
<p>]</p>
<p>Of course, you'd rarely write all of those in one declaration.
Most declarations only use one or two of them.  Or three or four...
Or five or six...</p>
<p>There is some flexibility in how you pass some of these parameters,
but the ordering of both formal parameters and actual arguments is
constrained in several ways.  For instance, positional parameters must
precede non-positional, and required parameters must precede optional.
Variadic lists must be attached either to the end of the positional
list or the end of the named parameter list.  These constraints serve
a number of purposes:</p>
<ul>
<li><a name='They avoid user confusion.'></a>They avoid user confusion.</li>
<li><a name='They enable the system to implement calls efficiently.'></a>They enable the system to implement calls efficiently.</li>
<li><a name='Perhaps most importantly, they allow interfaces to evolve without breaking old code.'></a>Perhaps most importantly, they allow interfaces to evolve without
breaking old code.</li>
</ul>
<p>Since there are constraints on the ordering of parameters, similar
parameters tend to clump together into &quot;zones&quot;.  So we'll call the
<code>?</code>, <code>+</code>, and <code>*</code> symbols you see above &quot;zone markers&quot;.  The
underlying metaphor really is very much like zoning regulations--you
know, the ones where your city tells you what you may or may not do
on a chunk of land you think you own.  Each zone has a set of possible
uses, and similar zones often have overlapping uses.  But you're still
in trouble if you put a factory in the middle of a housing division,
just as you're in trouble if you pass a positional argument to a
formal parameter that has no position.</p>
<p>I was originally going to go with a semicolon to separate required
from optional parameters (as Perl 5 uses in its prototypes), but I
realized that it would get lost in the traffic, visually speaking.
It's better to have the zone markers line up, especially if you decide
to repeat them in the vertical style:</p>
<pre>    method action ($self:
		int  $x,
		int ?$y,
		int ?$z,
	     Adverb +$how,
	Beneficiary +$for,
	   Location +$at is copy,
	   Location +$toward is copy,
	   Location +$from is copy,
	     Reason +$why,
	            *%named,
		    *@list
		) {...}</pre>
<p>So optional parameters are all marked with zone markers.</p>
<p>In this section we'll be concentrating on the declaration's syntax
rather than the call's syntax, though the two cannot be completely
disintertwingled.  The declaration syntax is actually the more
complicated of the two for various good reasons, so don't get too
discouraged just yet.</p>
<a name='Positional parameters'></a><h3>Positional parameters</h3>
<p>The three positional parameter types are the invocant, the required
parameters, and the optional positional parameters.  (Note that in
general, positional parameters may also be called using named parameter
notation, but they must be declared as positional parameters if you
wish to have the <i>option</i> of calling them as positional parameters.)
All positional parameters regardless of their type are considered
scalars, and imply scalar context for the actual arguments.  If you
pass an array or hash to such a parameter, it will actually pass
a reference to the array or hash, just as if you'd backslashed the
actual argument.</p>
<a name='The invocant'></a><h4>The invocant</h4>
<p>The first argument to any method (or submethod) is its invocant, that
is, the object or class upon which the method is acting.  The invocant
parameter, if present, is always declared with a colon following it.
The invocant is optional in the sense that, if there's no colon,
there's no explicit invocant declared.  It's still there, and it must
be passed by the caller, but it has no name, and merely sets the outer
topic of the method.  That is, the invocant's name is <code>$_</code>, at least
until something overrides the current topic.  (You can always get at
the invocant with the <code>self</code> built-in, however.  If you don't like
&quot;self&quot;, you can change it with a macro.  See below.)</p>
<p>[Update: The topic is not set now unless you explicitly name the
invocant &quot;<code>$_</code>&quot;.]</p>
<p>Ordinary subs never have an invocant.  If you want to declare a
non-method subroutine that behaves as a method, you should declare
a submethod instead.</p>
<p>Multimethods can have multiple invocants.  A colon terminates the list
of invocants, so if there is no colon, all parameters are considered
invocants.  Only invocants participate in multimethod dispatch.
Only the first invocant is bound to <code>$_</code>.</p>
<p>[Update: Again, only if you actually name that parameter &quot;<code>$_</code>&quot;.]</p>
<p>Macros are considered methods on the current parse state object,
so they have an invocant.</p>
<p>[Update: The current parse state object is now called <code>$?PARSER</code>, so
macros are now more like subroutines.]</p>
<a name='Required parameters'></a><h4>Required parameters</h4>
<p>Next (or first in the case of subs) come the required positional
parameters.  If, for instance, the routine declares three of these,
you have to pass at least three arguments in the same order.  The list
of required parameters is terminated at the first optional parameter,
that is the first parameter having any kind of zone marker.  If none
of those are found, all the parameters are required, and if you pass
either too many or too few arguments, Perl will throw an exception
as soon as it notices.  (That might be at either compile time or run
time.)  If there are optional or variadic parameters, the required
list merely serves as the minimum number of arguments you're allowed
to pass.</p>
<a name='Optional parameters'></a><h4>Optional parameters</h4>
<p>Next come the optional positional parameters.  (They have to come next
because they're positional.)  In the declaration, optional positional
parameters are distinguished from required parameters by marking the
optional parameters with a question mark.  (The parameters are not
distinguished in the call--you just use commas.  We'll discuss call
syntax later.)  All optional positional parameters are marked with
<code>?</code>, not just the first one.  Once you've made the transition to the
optional parameter zone, all parameters are considered optional from
there to the end of the signature, even after you switch zones to
<code>+</code> or <code>*</code>.  But once you leave the positional zone (at the end
of the <code>?</code> zone), you can't switch back to the positional zone,
because positionals may not follow variadics.</p>
<p>If there are no variadic parameters following the optional parameters,
the declaration establishes both a minimum and a maximum number of
allowed arguments.  And again, Perl will complain when it notices
you violating either constraint.  So the declaration:</p>
<pre>    sub *substr ($string, ?$offset, ?$length, ?$repl) {...}</pre>
<p>says that <code>substr</code> can be called with anywhere from 1 to 4 scalar
parameters.</p>
<p>[Update: Now written:</p>
<pre>    sub *substr ($string, $offset?, $length?, $repl?) {...}</pre>
<p>because the <code>?</code> is often replaced by a default.]</p>
<a name='Variadic parameters'></a><h3>Variadic parameters</h3>
<p>Following the positional parameters, three kinds of variadic parameters
may be declared.  Variadic arguments may be slurped into a hash or
an array depending on whether they look like named arguments or not.
&quot;Slurpy&quot; parameters are denoted by a unary <code>*</code> before the variable
name, which indicates that an arbitrary number of values is expected
for that variable.</p>
<p>Additional named parameters may be placed at the end of the
declaration, or marked with a unary <code>+</code> (because they're &quot;extra&quot;
parameters).  Since they are--by definition--in the variadic region,
they may only be passed as named arguments, never positionally.  It is
illegal to mark a parameter with <code>?</code> after the first <code>+</code> or <code>*</code>,
because you can't reenter a positional zone from a variadic zone.</p>
<p>Unlike the positional parameters, the variadic parameters are not
necessarily declared in the same order as they will be passed in the
call.  They may be declared in any order (though the exact behavior
of a slurpy array depends slightly on whether you declare it first
or last).</p>
<p>[Update: The behavior of a slurpy array is the same now regardless of
whether there are any named parameters in front of it.  And named
parameters are now marked with <code>:</code> rather than <code>+</code>.]</p>
<a name='Named-only parameters'></a><h4>Named-only parameters</h4>
<p>Parameters marked with a <code>+</code> zone marker are named-only parameters.
Such a parameter may never be passed positionally, but only by name.</p>
<p>[Update: Now using <code>:</code> instead.]</p>
<a name='The slurpy hash'></a><h4>The slurpy hash</h4>
<p>A hash declaration like <code>*%named</code> indicates that the <code>%named</code>
hash should slurp up all the remaining named arguments (that is,
those that aren't bound explicitly to a specific formal parameter).</p>
<a name='The slurpy array'></a><h4>The slurpy array</h4>
<p>An array declaration like <code>*@rest</code> indicates that the <code>@rest</code> array
should slurp up all the remaining items after the named parameters.
(Later we'll discuss how to disambiguate the situation when the
beginning of your list looks like named parameters.)  If you <code>shift</code>
or <code>pop</code> without an argument, it shifts or pops whatever slurpy array
is in scope.  (So in a sense, your main program has an implicit slurpy
array of <code>*@*ARGS</code> because that's what <code>shift</code> shifts there.)</p>
<a name='Formal parameter syntax'></a><h3>Formal parameter syntax</h3>
<p>Formal parameters have lexical scope, as if they were declared with
a <code>my</code>.  (That is reflected in the pseudocode in Appendix B.)
Their scope extends only to the end of the associated block.
Formal parameters are the only lexically scoped variables that are
allowed to be declared outside their blocks.  (Ordinary <code>my</code> and
<code>our</code> declarations are always scoped to their surrounding block.)</p>
<p>Any subroutine can have a method signature syntactically, but
subsequent semantic analysis will reject mistakes like invocants on
subroutines.  This is not just motivated by laziness.  I think that
&quot;<code>You can't have an invocant on a subroutine</code>&quot; is a better error
message than &quot;<code>Syntax error</code>&quot;.</p>
<pre>    rule signature :w {
	[&lt;parameter&gt; [&lt;[,:]&gt; &lt;parameter&gt; ]* ]?
    }</pre>
<p>In fact, we just treat colon as a funny comma here, so any use of
extra colons is detected in semantic analysis.  Similarly, zone
markers are semantically restricted, not syntactically.  Again,
&quot;<code>Syntax error</code>&quot; doesn't tell you much.  It's much more informative
to see &quot;<code>You can't declare an optional positional parameter like
?$flag after a slurpy parameter like *@list</code>&quot;, or &quot;<code>You can't use
a zone marker on an invocant</code>&quot;.</p>
<p>Here's what an individual parameter looks like:</p>
<pre>    rule parameter :w {
	[ &lt;type&gt;? &lt;zone&gt;? &lt;variable&gt; &lt;trait&gt;* &lt;defval&gt;?
	| \[ &lt;signature&gt; \]	# treat single array ref as an arg list
	]
    }

    rule zone {
	[ \?		# optional positional
	| \*		# slurpy array or hash
	| \+		# optional named-only
	]
    }

    rule variable { &lt;sigil&gt; &lt;name&gt; [ \( &lt;siglet&gt; \) ]? }
    rule sigil { &lt;[$@%&amp;]&gt; &lt;[*.?^]&gt;? }	# &quot;What is that, swearing?&quot;</pre>
<p>Likewise, we parse any sigil here, but semantically reject things like <code>$*x</code>
or <code>$?x</code>.  We also reject package-qualified names and indirect names.
We could have a <code>&lt;simplevar&gt;</code> rule that only admits <code>&lt;ident&gt;</code>,
but again, &quot;<code>Syntax error</code>&quot; is a lot less user-friendly than &quot;<code>You can't
use a package variable as a parameter, dimwit!</code>&quot;</p>
<p>Similarly, the optional <code>&lt;siglet&gt;</code> in <code>&lt;variable&gt;</code> is allowed
only on <code>&amp;</code> parameters, to say what you expect the signature of
the referenced subroutine to look like.  We should talk about siglets.</p>
<a name='Siglets'></a><h4>Siglets</h4>
<p>The <code>&lt;siglet&gt;</code> in the <code>&lt;variable&gt;</code> rule is an example of
a nameless signature, that is, a &quot;small signature&quot;, or &quot;siglet&quot;.
Signatures without names are also used for return types and context
traits (explained later).  A siglet is sequential list of paramlets.
The paramlets do not refer to actual variable names, nor do they
take defaults:</p>
<pre>    rule siglet :w {
	[&lt;paramlet&gt; [&lt;[,:]&gt; &lt;paramlet&gt; ]* ]?
    }

    rule paramlet :w {
	[ &lt;type&gt; &lt;zone&gt;? &lt;varlet&gt;? &lt;trait&gt;*	# require type
	| &lt;zone&gt; &lt;varlet&gt;? &lt;trait&gt;*		# or zone
	| &lt;varlet&gt; &lt;trait&gt;*			# or varlet
	| \[ &lt;siglet&gt; \]	# treat single array ref as an arg list
	]
    }</pre>
<p>In place of a <code>&lt;variable&gt;</code>, there's a kind of stub we'll call a &quot;varlet&quot;:</p>
<pre>    rule varlet :w {
	&lt;sigil&gt; [ \( &lt;siglet \) ]?
    }</pre>
<p>As with the <code>&lt;variable&gt;</code> rule, a <code>&lt;varlet&gt;</code>'s optional
siglet is allowed only on <code>&amp;</code> parameters.</p>
<p>Here's a fancy example with one signature and several siglets.</p>
<pre>    sub (int *@) imap ((int *@) &amp;block(int $),
    			int *@vector is context(int) {...}</pre>
<p>You're not expected to understand all of that yet.  What you should
notice, however, is that a paramlet is allowed to be reduced to
a type (such as <code>int</code>), or a zone (such as <code>?</code>), or a varlet (such as <code>$</code>), or some sequence
of those (such as <code>int *@</code>).  But it's not allowed to be reduced to a null
string.  A signature of <code>()</code> indicates zero arguments, not one argument
that could be anything.  Use <code>($)</code> for that.  Nor can you specify four
arguments by saying <code>(,,,)</code>.  You have to put something there.</p>
<p>Perl 6 siglets can boil down to something very much like Perl 5's
&quot;prototype pills&quot;.  However, you can't leave out the comma between
parameters in Perl 6.  So you have to say <code>($,$)</code> rather than <code>($$)</code>,
when you want to indicate a list of two scalars.</p>
<p>If you use a <code>&lt;siglet&gt;</code> instead of a <code>&lt;signature&gt;</code>
in declaring a subroutine, it will be taken as a Perl 5 style
prototype, and all args still come in via <code>@_</code>.  This is a sop to
the Perl5-to-Perl6 translator, which may not be able to figure out
how to translate a prototype to a signature if you've done something
strange with <code>@_</code>.  You should not use this feature in new code.
If you use a siglet on a stub declaration, you must use the same siglet
on the corresponding definition as well, and vice versa.  You can't
mix siglets and signatures that way.  (This is not a special rule,
but a natural consequence of the signature matching rules.)</p>
<a name='Siglets and multimethods'></a><h4>Siglets and multimethods</h4>
<p>For closure parameters like <code>&amp;block(int $)</code>, the associated siglet
is considered part of its name.  This is true not just for parameters,
but anywhere you use the <code>&amp;</code> form in your program, because with
multimethods there may be several routines sharing the same identifier,
distinguishable only by their type signature:</p>
<pre>    multi factorial(int $a) { $a&lt;=1 ?? 1 :: $a*factorial($a-1) }
    multi factorial(num $a) { gamma(1+$a) }

    $ref = &amp;factorial;		# illegal--too ambiguous
    $ref = &amp;factorial($);	# illegal--too ambiguous
    $ref = &amp;factorial(int);	# good, means first one.
    $ref = &amp;factorial(num);	# good, means second one.
    $ref = &amp;factorial(complex);	# bad, no such multimethod.</pre>
<p>Note that when following a name like &quot;<code>&amp;factorial</code>&quot;, parentheses do not
automatically mean to make a call to the subroutine.  (This Apocalypse
contradicts earlier Apocalypses.  Guess which one is right...)</p>
<p>[Update: Er, actually, the earlier Apocalypse is right.  We now write
those references above as <code>&amp;factorial:(complex)</code> and such.]</p>
<pre>    $val = &amp;factorial($x);	# illegal, must use either
    $val = factorial($x);	#   this or
    $val = &amp;factorial.($x);	#   maybe this.</pre>
<p>In general, don't use the <code>&amp;</code> form when you really want to call
something.</p>
<a name='Formal parameter traits'></a><h3>Formal parameter traits</h3>
<p>Other than type, zone, and variable name, all other information about
parameters is specified by the standard trait syntax, generally
introduced by <code>is</code>.  Internally even the type and zone are just
traits, but syntactically they're out in front for psychological
reasons.  <i>Whose</i> psychological reasons we won't discuss.</p>
<a name='is constant (default)'></a><h4><code>is constant</code> (default)</h4>
<p>Every formal parameter is constant by default, meaning primarily that
the compiler won't feel obligated to construct an lvalue out the actual
argument unless you specifically tell it to.  It also means that you
may not modify the parameter variable in any way.  If the parameter is
a reference, you may use it to modify the referenced object (if the
object lets you), but you can't assign to it and change the original
variable passed to the routine.</p>
<p>[Update: This is now the <code>readonly</code> trait.  We now prefer to reserve
the term &quot;constant&quot; to refer only to compile-time constants, and
parameters naturally tend to vary at run time.  Or so we hope.]</p>
<a name='is rw'></a><h4><code>is rw</code></h4>
<p>The <code>rw</code> trait is how you tell the compiler to ask for an lvalue
when evaluating the actual argument for this parameter.  Do not
confuse this with the <code>rw</code> trait on the subroutine as a whole, which
says that the entire subroutine knows how to function as an lvalue.
If you set this trait, then you may modify the variable that was
passed as the actual argument.  A <code>swap</code> routine would be:</p>
<pre>    sub swap ($a is rw, $b is rw) { ($a,$b) = ($b,$a) }</pre>
<p>If applied to a slurpy parameter, the <code>rw</code> trait distributes to each
element of the list that is bound to the parameter.  In the case of
a slurpy hash, this implies that the named pairs are in an lvalue
context, which actually puts the right side of each named pair into
lvalue context.</p>
<p>Since normal lvalues assume &quot;<code>is rw</code>&quot;, I suppose that also implies
that you can assign to a pair:</p>
<pre>    (key =&gt; $var) = &quot;value&quot;;</pre>
<p>or even do named parameter binding:</p>
<pre>    (who =&gt; $name, why =&gt; $reason) := (why =&gt; $because, who =&gt; &quot;me&quot;);</pre>
<p>which is the same as:</p>
<pre>    $name   := &quot;me&quot;;
    $reason := $because;</pre>
<p>And since a slurpy hash soaks up the rest of the named parameters,
this also seems to imply that binding a slurpy <code>rw</code> hash actually
makes the hash values into <code>rw</code> aliases:</p>
<pre>    $a = &quot;a&quot;; $b = &quot;b&quot;;
    *%hash := (a =&gt; $a, b =&gt; $b);
    %hash{a} = 'x';
    print $a;   # prints &quot;x&quot;</pre>
<p>That's kinda scary powerful.  I'm not sure I want to document that...
[&quot;Too late!&quot; whispers Evil Damian.]</p>
<a name='is copy'></a><h4><code>is copy</code></h4>
<p>This trait requests copy-in semantics.  The variable is modifiable
by you, but you're only modifying your own private copy.  It has the
same effects as assigning the argument to your own <code>my</code> variable.
It does <i>not</i> do copy-out.</p>
<p>If you want both copy-in and copy-out semantics, declare it <code>rw</code>
and do your own copying back and forth, preferably with something
that works even if you exit by exception (if that's what you want):</p>
<pre>    sub cico ($x is rw) {
	my $copy = $x;
	LAST { $x = $copy }
	...
    }</pre>
<p>Though if you're using a copy you probably only want to copy-out on
success, so you'd use a <code>KEEP</code> block instead.  Or more succinctly,
using the new <code>will</code> syntax:</p>
<pre>    sub cicomaybe ($x is rw) {
	my $copy will keep { $x = $copy } = $x;
	...
    }</pre>
<a name='is ref'></a><h4><code>is ref</code></h4>
<p>This trait explicitly requests call-by-reference semantics.  It lets
you read and write an existing argument but doesn't attempt to coerce
that argument to an lvalue (or autovivify it) on the caller end,
as <code>rw</code> would.  This trait is distinguished from a parameter of type
<code>Ref</code>, which merely asserts that the return type of the parameter is a
reference without necessarily saying anything about calling convention.
You can without contradiction say:</p>
<pre>    sub copyref (Ref $ref is copy) {...}</pre>
<p>meaning you can modify <code>$ref</code>, but that doesn't change whatever was
passed as the argument for that parameter.</p>
<a name='Defaults'></a><h4>Defaults</h4>
<p>Default values are also traits, but are written as assignments and
must come at the end of the formal parameter for psychological reasons.</p>
<pre>    rule defval :w { \= &lt;item&gt; }</pre>
<p>That is:</p>
<pre>    sub trim ( Str $_ is rw, Rule ?$remove = /\s+/ ) {
	    s:each/^ &lt;$remove&gt; | &lt;$remove&gt; $//;
    }</pre>
<p>lets you call <code>trim</code> as either:</p>
<pre>    trim($input);</pre>
<p>or:</p>
<pre>    trim($input, /\n+/);</pre>
<p>It's very important to understand that the expression denoted by
<code>item</code> is evaluated in the lexical scope of the subroutine definition,
not of the caller.  If you want to get at the lexical scope of the
caller, you have to do it explicitly (see <code>CALLER::</code> below).  Note
also that an <code>item</code> may not contain unbracketed commas, or the parser
wouldn't be able to reliably locate the next parameter declaration.</p>
<p>Although the default looks like an assignment, it isn't one.  Nor is
it exactly equivalent to <code>//=</code>, because the default is set only
if the parameter doesn't exist, not if it exists but is undefined.
That is, it's used only if no argument is bound to the parameter.</p>
<p>An <code>rw</code> parameter may only default to a valid lvalue.  If you find
yourself wanting it to default to an ordinary value because it's
undefined, perhaps you really want <code>//=</code> instead:</p>
<pre>    sub multprob ($x is rw, $y) {
	$x //= 1.0;	# assume undef means &quot;is certain&quot;
	$x *= $y;
    }</pre>
<p>Syntactically, you can put a default on a required parameter, but it
would never be used because the argument always exists.  So semantic
analysis will complain about it.  (And I'd rather not say that adding
a default implies it's optional without the <code>?</code> zone marker.)</p>
<p>[Update: By moving the <code>?</code> to the end, it now may be omitted as
redundant if there is a default.  That is, <code>$x?</code> is really short for
&quot; <code>$x = undef</code>&quot;.]</p>
<a name='Formal parameter types'></a><h3>Formal parameter types</h3>
<p>Formal parameters may have any type that any other variable may
have, though particular parameters may have particular
restrictions.  An invocant needs to be an object of an appropriate
class or subclass, for instance.  As with ordinary variable
declarations the type in front is actually the return type, and you
can put it afterwards if you like:</p>
<pre>    sub foo (int @array is rw) {...}
    sub foo (@array of int is rw) {...}
    sub foo (@array is Array of int is rw) {...}</pre>
<p>The type of the actual argument passed must be compatible with
(but not necessarily identical to) the formal type.  In particular,
for methods the formal type will often indicate a base class of the
actual's derived class.  People coming from C++ must remember that all
methods are &quot;virtual&quot; in Perl.</p>
<p>[Update: Beyond that, most of the types specified in signatures are
not even classes, but just roles used to name an interface.  See S12.]</p>
<p>Closure parameters are typically declared with <code>&amp;</code>:</p>
<pre>    sub mygrep (&amp;block, *@list is rw) {...}</pre>
<p>Within that subroutine, you can then call <code>block()</code> as an ordinary
subroutine with a lexically scoped name.  If such a parameter is
declared without its own parameter signature, the code makes no
assumptions about the actual signature of the closure supplied as
the actual argument.  (You can always inspect the actual signature
at run time, of course.)</p>
<p>You may, however, supply a signature if you like:</p>
<pre>    sub mygrep (&amp;block($foo), *@list is rw) {
	block(foo =&gt; $bar);
    }</pre>
<p>[Update: That can be written <code>&amp;block:($foo)</code> now.]</p>
<p>With an explicit signature, it would be error to bind a block to
<code>&amp;block</code> that is not compatible.  We're leaving &quot;compatible&quot; undefined
for the moment, other than to point out that the signature doesn't have
to be identical to be compatible.  If the actual subroutine accepted
one required parameter and one optional, it would work perfectly fine,
for instance.  The signature in <code>mygrep</code> is merely specifying what
it requires of the subroutine, namely one positional argument named
&quot;<code>$foo</code>&quot;.  (Conceivably it could even be named something different
in the actual routine, provided the compiler turns that call into a
positional one because it thinks it already knows the signature.)</p>
<a name='Calling subroutines'></a><h2>Calling subroutines</h2>
<p>The typical subroutine or method is called a lot more often than
it is declared.  So while the declaration syntax is rather ornate,
we strive for a call syntax that is rather simple.  Typically it
just looks like a comma-separated list.  Parentheses are optional on
predeclared subroutine calls, but mandatory otherwise.  Parentheses
are mandatory on method calls with arguments, but may be omitted
for argumentless calls to methods such as attribute accessors.
Parentheses are optional on multimethod and macro calls because they
always parse like list operators.  A rule may be called like a method
but is normally invoked within a regex via the <code>&lt;rule&gt;</code> syntax.</p>
<p>[Update: Parentheses are optional on &quot;postdeclared&quot; subroutines as well,
provided the post-declaration is consistent with listop syntax.]</p>
<p>As in Perl 5, within the list there may be an implicit transition
from scalar to list context.  For example, the declaration of the
standard <code>push</code> built-in in Perl 6 probably looks like this:</p>
<pre>    multi *push (@array, *@list) {...}</pre>
<p>but you still generally call it as you would in Perl 5:</p>
<pre>    push(@foo, 1, 2, 3);</pre>
<p>This call has two of the three kinds of call arguments.  It has one
positional argument, followed by a variadic list.  We could imagine
adding options to <code>push</code> sometime in the future.  We <i>could</i> define
it like this:</p>
<pre>    multi *push (@array, ?$how, *@list) {...}</pre>
<p>That's just an optional positional parameter, so you'd call it
like this:</p>
<pre>    push(@foo, &quot;rapidly&quot;, 1,2,3)</pre>
<p>But that won't do, actually, since we used to allow the list to
start at the end of the positional parameters, and any pre-existing
<code>push(@foo,1,2,3)</code> call to the new declaration would end up mapping
the &quot;<code>1</code>&quot; onto the new optional parameter.  Oops...</p>
<p>If instead we force new parameters to be in named notation, like this:</p>
<pre>    multi *push (@array, *@list, +$how) {...}</pre>
<p>then we can say:</p>
<pre>    push(@foo, how =&gt; &quot;rapidly&quot;, 1,2,3)</pre>
<p>and it's no longer ambiguous.  Since <code>$how</code> is in the named-only zone,
it can never be set positionally, and the old calls to:</p>
<pre>    push(@foo, 1,2,3);</pre>
<p>still work fine, because <code>*@list</code> is still at the end of the
positional parameter zone.  If we instead declare that:</p>
<pre>    multi *push (@array, +$how, *@list) {...}</pre>
<p>we could still say:</p>
<pre>    push(@foo, how =&gt; &quot;rapidly&quot;, 1,2,3)</pre>
<p>but this becomes illegal:</p>
<pre>    push(@foo, 1,2,3);</pre>
<p>[Update: Actually, it's still legal now.]</p>
<p>because the slurpy array is in the named-only zone.  We'll need an
explicit way to indicate the start of the list in this case.  I can
think of lots of (mostly bad) ways.  You probably can too.  We'll
come back to this...</p>
<a name='Actual arguments'></a><h3>Actual arguments</h3>
<p>So the actual arguments to a Perl function are of three kinds:
positional, named, and list.  Any or all of these parts may be omitted,
but whenever they are there, they <i>must</i> occur in that order.  It's
more efficient for the compiler (and less confusing to the programmer)
if all the positional arguments come before all the non-positional
arguments in the list.  Likewise, the named arguments are constrained
to occur before the list arguments for efficiency--otherwise the
implementation would have to scan the entire list for named arguments,
and some lists are monstrous huge.</p>
<p>[Update: These are now viewed as suggestions rather than hard rules.]</p>
<p>We'd call these three parts &quot;zones&quot; as well, but then people
would get them confused with our six declarative zones.  In fact,
extending the zoning metaphor a bit, our three parts are more like
houses, stores, and factories (real ones, not OO ones, sheesh).
These are the kinds of things you actually <i>find</i> in residential,
commercial, and industrial zones.  Similarly, you can think of the
three different kinds of argument as the things you're allowed to
<i>bind</i> in the different parameter zones.</p>
<p>A house is generally a scalar item that is known for its position;
after all, &quot;there's no <i>place</i> like home&quot;.  Um, yeah.  Anyway,
we usually number our houses.  In the US, we don't usually name our
houses, though in the UK they don't seem to mind it.</p>
<p>A store may have a position (a street number), but usually we refer
to stores by name.  &quot;I'm going out to Fry's&quot; does not refer to a
particular location, at least not here in Silicon Valley.  &quot;I'm going
out to McDonald's&quot; doesn't mean a particular location anywhere in
the world, with the possible exception of &quot;not Antarctica&quot;.</p>
<p>You don't really care exactly where a factory is--as long as it's not
in your back yard--you care what it produces.  The typical factory is
for mass producing a series of similar things.  In programming terms,
that's like a generator, or a pipe...or a list.  And you mostly worry
about how you get vast quantities of stuff into and out of the factory
without keeping the neighbors awake at night.</p>
<p>So our three kinds of arguments map onto the various parameter zones
in a similar fashion.</p>
<a name='The positional arguments'></a><h4>The positional arguments</h4>
<p>Obviously, actual positional arguments are mapped onto the formal
parameters in the order in which the formal positional parameters
are declared.  Invocant parameters (if any) must match invocant
arguments, the required parameters match positional arguments, and
then any additional non-named arguments are mapped onto the optional
positional parameters.  However, as soon as the first named argument is
seen (that cannot be mapped to an explicitly typed <code>Pair</code> or <code>Hash</code>
parameter) this mapping stops, and any subsequent positional parameters
may only be bound by name.</p>
<p>[Update: Named arguments are now distinguished syntactically from <code>Pair</code>
arguments, so it's not necessary to do type matching.]</p>
<a name='The named arguments'></a><h4>The named arguments</h4>
<p>After the positional argument part, you may pass as many named pairs
as you like.  These may bind to any formal parameter named in the
declaration, whether declared as positional or named.  However, it
is erroneous to simultaneously bind a parameter both by position and
by name.  Perl may (but is not required to) give you a warning or error
about this.  If the problem is ignored, the positional parameter takes
precedence, since the name collision might have come in by accident as
a result of passing extra arguments intended for a different routine.
Problems like this can arise when passing optional arguments to all
the base classes of the current class, for instance.  It's not yet
clear how fail-soft we should be here.</p>
<p>Named arguments can come in either as <code>Pair</code> or <code>Hash</code> references.
When parameter mapper sees an argument that is neither a <code>Pair</code> nor a
<code>Hash</code>, it assumes it's the end of the named part and the beginning of
the list part.</p>
<p>All unbound named arguments are bound to elements of the slurpy hash,
if one was declared.  If no slurpy hash is declared, an exception is
thrown (although some standard methods, like <code>BUILD</code>, will provide
an implicitly declared slurpy hash--known as <code>%_</code> by analogy
to <code>@_</code>--to handle surplus named arguments).</p>
<p>At the end of named argument processing, any unmapped optional
parameter ends up with the value <code>undef</code> unless a default value is
declared for it.  Any unmapped required parameter throws an exception.</p>
<a name='The slurpy array'></a><h4>The slurpy array</h4>
<p>All remaining arguments are bound to the slurpy array, if any.  If no
slurpy array is specified, any remaining arguments cause an exception
to be thrown.  (You only get an implicit <code>*@_</code> slurpy array when the
signature is omitted entirely. Otherwise we could never validly give
the error &quot;Too many arguments&quot;.)</p>
<p>No argument processing is done on this list.  If you go back to using
named pairs at the end of the list, for instance, you'll have to pop
those off yourself.  But since the list is potentially very long, Perl
isn't going to look for those on your behalf.</p>
<p>Indeed, the list could be infinitely long, and maybe even a little
longer than that.  Perl 5 always flattens lists before calling the
subroutine.  In Perl 6, list flattening is done lazily, so a list
could contain several infinite entries:</p>
<pre>    print(1..Inf, 1..Inf);</pre>
<p>That might eventually give the <code>print</code> function heartburn, of course...</p>
<a name='Variadic transitions'></a><h3>Variadic transitions</h3>
<p>There are, then, two basic transitions in argument processing.  First
is the transition from positional to named arguments.  The second is
from named arguments to the variadic list.  It's also possible to
transition directly from positional arguments to the variadic list
if optional positional arguments have been completely specified.
That is, the slurp array could just be considered the next optional
positional parameter in that case, as it is in <code>push</code>.</p>
<p>But what if you don't want to fill out all the optional parameters, and
you aren't planning to use named notation to skip the rest of them?
How can you make both transitions simultaneously?  There are two
workarounds.  First, suppose we have a <code>push</code>-like signature such
as this:</p>
<pre>    sub stuff (@array, ?$how, *@list) {...}</pre>
<p>The declarative workaround is to move the optional parameters after
the slurp array, so that they are required to be specified as named
parameters:</p>
<pre>    sub stuff (@array, *@list, +$how) {...}</pre>
<p>Then you can treat the slurp array as a positional parameter.
That's the solution we used to add an extra argument to <code>push</code>
earlier, where the list always starts at the second argument.</p>
<p>[Update: The slurpy array is now always treated as a positional
parameter even if there are named parameters intervening.]</p>
<p>On the calling end, you don't have any control of the declaration,
but you can always specify one of the arguments as named, either the
final positional one, or the list itself:</p>
<pre>    stuff(@foo, how =&gt; undef, 1,2,3)
    stuff(@foo, list =&gt; (1,2,3))</pre>
<p>The latter is clearer and arguably more correct, but it has a couple
of minor problems.  For one thing, you have to know what the parameter
name is.  It's all very well if you have to know the names of optional
parameters, but <i>every</i> list operator has a list that you really
ought to be able to feed without knowing its name.</p>
<p>So we'll just say that the actual name of the slurpy list parameter is
&quot;<code>*@</code>&quot;.  You can always say this:</p>
<pre>    stuff(@foo, '*@' =&gt; (1,2,3))</pre>
<p>[Update: Actually, it's the null name that maps to the slurpy list.]</p>
<p>That's still a lot of extra unnecessary cruft--but we can do better.
List operators are like commands in Unix, where there's a command line
containing a program name and some options, and streams of data coming
in and going out via pipes.  The command in this case is <code>stuff</code>,
and the option is <code>@foo</code>, which says what it is we're stuffing.
But what about the streams of stuff going in and out?  Perl 6 has
lazy lists, so they are in fact more like streams than they used to be.</p>
<p>There will be two new operators, called pipe operators, that allow us
to hook list generators together with list consumers in either order.
So either of these works:</p>
<pre>    stuff @foo &lt;== 1,2,3
    1,2,3 ==&gt; stuff @foo</pre>
<p>The (ir)rationale for this is provided in Appendix A.</p>
<p>To be sure, these newfangled pipe operators do still pass the
list as a &quot;<code>*@</code>&quot;-named argument, because that allows indirection in the
entire argument list.  Instead of:</p>
<pre>    1,2,3 ==&gt; stuff @foo</pre>
<p>you can pull everything out in front, including the positional and
named parameters, and build a list that gets passed as &quot;splat&quot;
arguments (described in the next section) to <code>stuff</code>:</p>
<pre>    list(@foo, how =&gt; 'scrambled' &lt;== 1,2,3)
	==&gt; stuff *;</pre>
<p>In other words:</p>
<pre>    list(@foo, how =&gt; 'scrambled' &lt;== 1,2,3) ==&gt; stuff *;</pre>
<p>is equivalent to:</p>
<pre>    list(@foo, how =&gt; 'scrambled' &lt;== 1,2,3) ==&gt; stuff *();</pre>
<p>which is equivalent to:</p>
<pre>    stuff *(list(@foo, how =&gt; 'scrambled' &lt;== 1,2,3));</pre>
<p>The &quot;splat&quot; and the <code>list</code> counteract each other, producing:</p>
<pre>    stuff(@foo, how =&gt; 'scrambled' &lt;== 1,2,3);</pre>
<p>So what <code>stuff</code> actually sees is exactly as if you called it like this:</p>
<pre>    stuff(@foo, how =&gt; 'scrambled', '*@' =&gt; (1,2,3));</pre>
<p>which is equivalent to:</p>
<pre>    stuff @foo, how =&gt; 'scrambled', 1, 2, 3;</pre>
<p>And yes, the <code>==&gt;</code> and <code>&lt;==</code> operators are big, fat, and
obnoxiously noticeable.  I like them that way.  I think the pipes
are important and <i>should</i> stand out.  In postmodern architecture
the ducts are just part of the deconstructed decor.  (Just don't
anyone suggest a <code>==&gt;=</code> operator.  Just...don't.)</p>
<p>The <code>==&gt;</code> and <code>&lt;==</code> operators have the additional side
effect of forcing their blunt end into list context and their pointy
end into scalar context.  (More precisely, it's not the expression
on the pointy end that is in scalar context, but rather the positional
arguments of whatever list function is pointed to by the pointy end.)
See Appendix A for details.</p>
<p>[Update: We also now have a slurpy routine, <code>*&amp;block</code>, that binds to
an anonymous adverbial block.]</p>
<a name='Context'></a><h3>Context</h3>
<p>As with Perl 5, the scalar arguments are evaluated in scalar context,
while the list arguments are evaluated in list context.  However,
there are a few wrinkles.</p>
<a name='Overriding signature with *'></a><h4>Overriding signature with <code>*</code></h4>
<p>Perl 5 has a syntax for calling a function without paying any attention
to its prototype, but in Perl 6 that syntax has been stolen for a
higher purpose (referential purity).  Also, sometimes you'd like to be
able to ignore part of a signature rather than the whole signature.
So Perl 6 has a different notation, unary <code>*</code>, for disabling
signature checking, which we've mentioned in earlier Apocalypses,
and which you've already seen in the form of the <code>stuff *</code> above.
(Our splat in the <code>stuff *</code> above is in fact unary, but the optional
argument is missing, because the list is supplied via pipe.)</p>
<p>The first splatted term in an argument list causes all prior terms
to be evaluated in scalar context, and all subsequent terms to be
evaluated in list context.  (Splat is a no-op in list context, so it
doesn't matter if there are more splatted terms.)  If the function
wants more positional arguments, they are assumed to come from the
generated list, as if the list had been specified literally in the
program at that point as comma-separated values.</p>
<p>[Update: This is now done using the <code>[,]</code> reduce operator.  For <code>*</code>
and &quot;splat&quot; below read <code>[,]</code> instead.]</p>
<p>With splat lists, some of the argument processing may have to be
deferred from compile time to runtime, so in general such a call may
run slower than the ordinary form.</p>
<a name='Context unknown at compile time'></a><h4>Context unknown at compile time</h4>
<p>If Perl can't figure out the signature of a function at compile time
(because, for instance, it's a method and not a function), then it
may not be known which arguments are in scalar or list context at
the time they are evaluated.  This doesn't matter for Perl variables,
because in Perl 6, they always return a reference in either scalar or
list context.  But if you call a function in such an indeterminate
context, and the function doesn't have a return value declared that
clarifies whether the function behaves differently in scalar or list
context, then one of two things must happen.  The function must either
run in an indeterminate context, or the actual call to the function
must be delayed until the context is known.  It is not yet clear
which of these approaches is the lesser evil.  It may well depend on
whether the function pays more attention to its dynamic context or
to global values.  A function with no side effects and no global or
dynamic dependencies can be called whenever we like, but we're not
here to enforce the functional paradigm.  Interesting functions may
pay attention to their context, and they may have side effects such
as reading from an input stream in a particular order.</p>
<p>A variant of running in indeterminate context is to simply assume the
function is running in list context.  (That is, after all, what Perl
5 does on methods and on not-yet-declared subroutines.)  In Perl 6,
we may see most such ambiguities resolved by explicit use of the <code>&lt;==</code>
operator to force preceding args into scalar context, and the
following args into list context.  Individual arguments may also be
forced into scalar or list context, of course.</p>
<p>By the way, if you mix unary splat with <code>&lt;==</code>, only the args
to the left of the splat are forced into scalar context.  (It can do
this because <code>&lt;==</code> governs everything back to the list operator,
since it has a precedence slightly looser than comma.)  So, given
something like:</p>
<pre>    @moreargs = (1,2,3);
    mumble $a, @b, c(), *@moreargs &lt;== @list;</pre>
<p>we can tell just by looking that <code>$a</code>, <code>@b</code>, and <code>c()</code> are all
evaluated in scalar context, while <code>@moreargs</code> and <code>@list</code> are both
in list context.  It is parsed like this:</p>
<pre>    mumble( ($a, @b, c(), (*@moreargs)) &lt;== (@list) );</pre>
<p>You might also write that like this:</p>
<pre>    @moreargs = list(1,2,3 &lt;== @list);
    mumble $a, @b, c(), *@moreargs;</pre>
<p>In this case, we can still assume that <code>$a</code>, <code>@b</code>, <code>c()</code> are in
scalar context, because as we mentioned in the previous section,
the <code>*</code> forces it.  (That's because there's no reason to put the
splat if you're already in list context.)</p>
<p>Before we continue, you probably need a break.  Here, have a break:</p>
<pre>    *******************************************************
    ******************** Intermission *********************
    *******************************************************</pre>
<a name='Variations on a theme'></a><h2>Variations on a theme</h2>
<p>Welcome back.</p>
<p>We've covered the basics up till now, but there are a number of
miscellaneous variations we left out in the interests of exposition.
We'll now go back to visit some of those issues.</p>
<a name='Typed slurps'></a><h3>Typed slurps</h3>
<p>Sometimes you want to specify that the variadic list has a particular
recurring type, or types.  This falls out naturally from the slurp
array syntax:</p>
<pre>    sub list_of_ints ($a, $b, Int *@ints) { ... }
    sub list_of_scalars (Scalar *@scalars) { ... }</pre>
<p>These still evaluate the list in list context.  But if you declare
them as:</p>
<pre>    sub intlist ($a, $b, Int *@ints is context(Int)) { ... }
    sub scalarlist (Scalar *@scalars is context(Scalar)) { ... }</pre>
<p>then these provide a list of <code>Int</code> or <code>Scalar</code> contexts to the
caller.  If you call:</p>
<pre>    scalarlist(@foo, %bar, baz())</pre>
<p>you get two scalar references and the scalar result of <code>baz()</code>, not a
flattened list.  You can have lists without list context in Perl 6!</p>
<p>[Update: But only on ordinary subs.]</p>
<p>If you want to have alternating types in your list, you can.
Just specify a tuple type on your context:</p>
<pre>    strintlist( *@strints is context(Str,Int)) { ... }</pre>
<p>Perl 5's list context did not do lazy evaluation, but always flattened
immediately.  In Perl 6 the default list context &quot;<code>is context(Lazy)</code>&quot;.
But you can specify &quot;<code>is context(Eager)</code>&quot; to get back to Perl 5
semantics of immediate flattening.</p>
<p>As a sop to the Perl5-to-Perl6 translator (and to people who have to
read translated programs), the <code>Eager</code> context can also be specified
by doubling the slurpy <code>*</code> on the list to make it look like a pair of
rollers that will squish anything flat:</p>
<pre>    sub p5func ($arg, **@list) { ... }</pre>
<p>The &quot;eager splat&quot; is also available as a unary operator to
attempt eager flattening on the rvalue side:</p>
<pre>    @foo = **1..Inf;  # Test our &quot;out of memory&quot; handler...</pre>
<p>[Update: this is now just done with the <code>eager</code> listop.]</p>
<a name='Sublist formals'></a><h3>Sublist formals</h3>
<p>It's often the case that you'd like to treat a single array argument
as if it were an argument list of its own.  Well, you can.  Just put
a sublist signature in square brackets.  This is particularly good
for declaring multimethods in a functional programming mindset:</p>
<pre>    multi apply (&amp;func, []) { }
    multi apply (&amp;func, [$head, *@tail]) {
	return func($head), apply(&amp;func, @tail);
    }

    @squares := apply { $_ * $_ } [1...];</pre>
<p>Of course, in this case, the first multimethod is never called because
the infinite list is never null no matter how many elements we pull
off the front.  But that merely means that <code>@squares</code> is bound to
an infinite list generator.  No big deal, as long as you don't try to
flatten the list...</p>
<p>Note that, unlike the example in the previous section which alternated
strings and integers, this:</p>
<pre>    strintlist( [Str, Int] *@strints ) { ... }</pre>
<p>implies single array references coming in, each containing a string
and an integer.</p>
<p>Of course, this may be a bad example insofar as we could just write:</p>
<pre>    multi apply (&amp;func) { }
    multi apply (&amp;func, $head, *@tail) {
	return func($head), apply(&amp;func, *@tail);
    }

    @squares := apply { $_ * $_ } *1...;</pre>
<p>It'd be nice to lose the <code>*</code> though on the calls.  Maybe what we
really want is a slurpy scalar in front of the slurpy array, where
presumably the <code>&lt;==</code> maps to the first slurpy scalar or hash
(or it could be passed positionally):</p>
<pre>    multi apply (&amp;func) { }
    multi apply (&amp;func, *$head, *@tail) {
	return func($head), apply(&amp;func &lt;== @tail);
    }

    @squares := apply { $_ * $_ } 1...;</pre>
<p>Yow, I think I could like that if I tried.</p>
<p>So let's say for now that a slurpy scalar parameter just pulls the
first (or next) value off of the the slurpy list.  The <code>[]</code> notation
is still useful though for when you really do have a single array
ref coming in as a parameter.</p>
<p>[Update: A slurpy scalar might also be bound to an unnamed adverbial
block if there is no slurpy block to bind it to.  Since named parameter
processing precedes slurpy list processing, any named parameter bound
to an adverbial block is automatically excluded from binding to the
slurpy list.]</p>
<a name='Attributive parameters'></a><h3>Attributive parameters</h3>
<p>It is typical in many languages to see object initializers that look
like this (give or take a keyword):</p>
<pre>    function init (a_arg, b_arg, c_arg) {
	a = a_arg;
	b = b_arg;
	c = c_arg;
    }</pre>
<p>Other languages <i>try</i> to improve the situation without actually
succeeding.  In a language resembling C++, it might look more like
this:</p>
<pre>    method init (int a_arg, int b_arg, int c_arg)
	: a(a_arg), b(b_arg), c(c_arg) {}</pre>
<p>But there's still an awful lot of redundancy there, not to mention
inconsistent special syntax.</p>
<p>Since (as proven by Perl 5) signatures are all about syntactic sugar
anyway, and since Perl 6 intentionally makes attribute variables
visually distinct from ordinary variables, we can simply write this
in Perl 6 as:</p>
<pre>    submethod BUILD ($.a, $.b, $.c) {}</pre>
<p>Any parameter that appears to be an attribute is immediately
copied directly into the corresponding object attribute, and no
lexical parameter is generated.  You can mix these with ordinary
parameters--the general rule of thumb for an initializer is that you
should see each dotted attribute at least once:</p>
<pre>    submethod BUILD ($.a, $.b, $c) {
	$.c = mung($c);
    }</pre>
<p>This feature is primarily intended for use in constructors and
initializers, but Perl does not try to guess which subroutines fall
into that category (other than the fact that Perl 6 will implicitly
call certain conventional names like CREATE and BUILD.)</p>
<p>However, submethods such as BUILD are assumed to have an extra
<code>*%_</code> parameter to soak up any extra unrecognized named arguments.
Ordinarily you must declare a slurp-hash explicitly to get
that behavior.  But BUILD submethods are always called with named
arguments (except for the invocant), and often have to ignore arguments
intended for other classes participating in the current construction.
It's likely that this implicit <code>*%_</code> feature extends to other routines
declared in all-caps as well, and perhaps all submethods.</p>
<p>[Update: Turns out that all methods and submethods work this way.]</p>
<p>As in Perl 5, subroutines declared in all-caps are expected to be
called automatically most of the time--but not necessarily all the
time.  The BUILD routine is a good example, because it's only called
automatically when you rely on the default class initialization rules.
But you can override those rules, in which case you may have to call
BUILD yourself.  More on that in Apocalypse 12.  Or go to one of
Damian's Perl 6 talks...</p>
<a name='Other kinds of subroutines'></a><h3>Other kinds of subroutines</h3>
<a name='Closures'></a><h4>Closures</h4>
<p>All blocks are considered closures in Perl 6, even the blocks
that declare modules or classes (presuming you use the block form).
A closure is just an anonymous subroutine that has access to its lexical
context.  The fact that some closures are immediately associated
with names or have other kinds of parameter declarations does not
change the fact that an anonymous bare block without parameters is
also a kind of subroutine.  Of course, if the compiler can determine
that the block is only executed inline, it's free to optimize away
all the subroutine linkage--but not the lexical linkage.  It can only
optimize away the lexical linkage if no external lexicals are accessed
(or potentially accessed, in the case of <code>eval</code>).</p>
<a name='Pointy subs'></a><h4>Pointy subs</h4>
<p>As introduced in Apocalypse 4, loops and topicalizers are often
written with a special form of closure declaration known these days
as &quot;pointy subs&quot;.  A pointy sub is exactly equivalent to a standard
anonymous sub declaration having the same parameters.  It's almost
pure syntactic sugar--except that we embrace syntactic sugar in Perl
when it serves a psychological purpose (not to be confused with a
logical psycho purpose, which we also have).</p>
<p>Anyway, when you say:</p>
<pre>    -&gt; $a, $b, $c { ... }</pre>
<p>it's almost exactly the same as if you'd said:</p>
<pre>    sub ($a, $b, $c) { ... }</pre>
<p>only without the parentheses, and with the cute arrow that indicates
the direction of data flow to that part of your brain that consumes
syntactic glucose at a prodigious rate.</p>
<p>Since the parentheses around the signature are missing, you can't
specify anything that would ordinarily go outside the parentheses,
such as the return type or other subroutine traits.  But you may
still put traits or zone markers on each individual formal parameter.</p>
<p>Also, as a &quot;sub-less&quot; declaration, you can't return from it using
<code>return</code>, because despite being a closure, it's supposed to <i>look</i>
like a bare <code>Block</code> embedded in a larger <code>Routine</code>, and users will
expect <code>return</code> to exit from the &quot;real&quot; subroutine.  All of which
just means that, if you need those fancy extras, use a real <code>sub</code>
sub, not a pointy one.</p>
<a name='Placeholders'></a><h4>Placeholders</h4>
<p>Also as discussed in Apocalypse 4, a bare block functioning as a
closure can have its parameters declared internally.  Such parameters
are of the form:</p>
<pre>    rule placeholder { &lt;sigil&gt; \^ &lt;ident&gt; }</pre>
<p>Placeholder parameters are equivalent to required position parameters
declared in alphabetical order.  (Er, Unicodical order, really.)
For example, the closure:</p>
<pre>    { $^fred &lt;=&gt; $^barney }</pre>
<p>has the same signature as the pointy sub:</p>
<pre>    -&gt; $barney, $fred { $fred &lt;=&gt; $barney }</pre>
<p>or the standard anonymous sub:</p>
<pre>    sub ($barney, $fred) { $fred &lt;=&gt; $barney }</pre>
<p>On first hearing about the alphabetical sorting policy, some otherwise
level-headed folks immediately panic, imagining all sorts of ways
to abuse the mechanism for the purposes of obfuscation.  And surely
there are many ways to abuse many of the features in Perl, more
so in Perl 6.  The point of this mechanism, however, is to make
it drop-dead easy to write small, self-contained closures with a
small number of parameters that you'd probably give single-character
alphabetical names to in any event.  If you want to get fancier than
that, you should probably be using a fancier kind of declaration.
I define &quot;small number&quot; as approximately <i>e</i> ± π.  But as
is generally the case in Perl, you get to pick your own definition of
&quot;small number&quot;.  (Or at the very least, you get to pick whether to
work with a company that has already defined &quot;small number&quot; for you.)</p>
<p>As bare rvalue variables embedded in the code, you may not put any
traits or zone markers on the placeholders.  Again, the desire
to do so indicates you should be using a fancier form of declaration.</p>
<a name='Methods'></a><h4>Methods</h4>
<p>Perl 5 just used subroutines for methods.  This is okay as long as
you don't want to declare any utility subroutines in your class.
But as soon as you do, they're inherited in Perl 5, which is not what
you want.  In Perl 6, methods and subroutines still share the same
namespace, but a method must be declared using the <code>method</code> keyword.
This is good documentation in any event, and further allows us to
intuit an invocant where none is declared.  (And we know that none
is declared if there's no colon after the first argument, at least
in the case of an ordinary method.)</p>
<a name='Submethods'></a><h4>Submethods</h4>
<p>There are certain implementation methods that want to be inherited in
general so that you can specify a default implementation, but that
you want the class to be able to override without letting derived
classes inherit the overridden method from this class.  That is,
they are scoped like utility subroutines, but can be called as if
they are methods, without being visible outside the class.  We call
these hybrids &quot;submethods&quot;, and so there's a <code>submethod</code> keyword
to declare them.  Submethods are simultaneously subs and methods.
You can also think of them as something less than a method, as the
&quot;sub&quot; works in the word &quot;subhuman&quot;.  Or you can think of them as
underneath in the infrastructural sense, as in &quot;subterranean&quot;.</p>
<p>Routines that create, initialize, or destroy the current object tend
to fall into this category.  Hence, the <code>BUILD</code> routine we mentioned
earlier is ordinarily declared as a submethod, if you don't want to
inherit the standard <code>BUILD</code> method defined in the Object class.  But
if you override it, your children still inherit <code>BUILD</code> from Object.</p>
<p>Contrariwise, if you don't like <code>Object</code>'s default <code>BUILD</code> method,
you can define an entire new class of classes that all default to
your own <code>BUILD</code> method, as long as those classes derive from your
new base object with superior characteristics.  Each of those derived
classes could then define a submethod to override your method only
for that class, while classes derived from those classes could still
inherit your default.</p>
<p>And so on, ad OOium.</p>
<a name='Multimethods'></a><h4>Multimethods</h4>
<p>Some kinds of programming map easily onto the standard model in which
a method has a single invocant.  Other kinds of programming don't.
Perl 6 supplies support for the latter kind of programming, where
the relationships between classes are just as interesting as the
classes themselves.  In some languages, all methods are multimethods.
Perl 6 doesn't go quite that far--you must declare your multimethods
explicitly.  To do so, use the <code>multi</code> keyword in place of <code>method</code>,
and optionally place a colon after the list of invocants in the
declaration, unless you want them all to be invocants.  Then your
multimethod will be registered globally as a being of interest to
all the types of its invocants, and will participate in multimethod
dispatch.</p>
<p>It is beyond the scope of this Apocalypse to specify exactly how
multimethod dispatch works (see Apocalypse 12, someday), but we can
tell you that, in general, you call a multimethod as if it were an
ordinary subroutine, and the dispatcher figures out on your behalf how
many of the arguments are invocants.  This may sound fancy to you, but
many of the functions that are built into Perl 5 are <i>not</i> built into
Perl 6, at least, not as keywords.  Instead they are either defined as
global subroutines or as multimethods, single invocant multimethods
in many cases.  When you call a function like <code>close($handle)</code>,
it'll first look to see if there's a <code>close</code> subroutine defined in
your scope, and if not, it will dispatch it as a multimethod.  Likewise,
for something like <code>sysread</code>, you can call it either as a method:</p>
<pre>    sysread $handle: $buffer, $length</pre>
<p>or as a function:</p>
<pre>    sysread $handle, $buffer, $length</pre>
<p>In the first case, it's explicitly dispatching on the handle,
because a colon in place of the first comma indicates an invocant.
(That's our new indirect object syntax, in fact.  Perl 6 does not
support the Perl 5 syntax of just leaving whitespace between the
indirect object and the subsequent arguments.)</p>
<p>In the second case, it looks for a <code>sysread</code> subroutine, doesn't find
it (we hope), and calls multimethod dispatch on it.  And it happens
that the multimethod dispatch is smart enough to find the ordinary
single-invocant <code>sysread</code> method, even though it may not have been
explicitly declared a multimethod.  Multimethod dispatch happens to map
directly onto ordinary method dispatch when there's only one invocant.</p>
<p>At least, that's how it works this week...</p>
<a name='Rules'></a><h4>Rules</h4>
<p>Rules were discussed in Apocalypse 5.  They are essentially methods
with an implicit invocant, consisting of the object containing the
current pattern matching context.  To match the internals of regex
syntax, traits attached to rules are typically written as &quot;<code>:w</code>&quot;
rather than &quot;<code>is w</code>&quot;, but they're essentially the same thing
underneath.</p>
<p>It's possible to call a rule as if it were a method, as long as
you give it the right arguments.  And a method defined in a grammar
can be called as if it were a rule.  They share the same namespace,
and a rule really is just a method with a funny syntax.</p>
<a name='Macros'></a><h4>Macros</h4>
<p>A macro is a function that is called immediately upon completion of
the parsing of its arguments.  Macros must be defined before they
are used--there are no forward declarations of macros, and while a
macro's name may be installed in either a package or a lexical scope,
its syntactic effect can only be lexical, from the point of declaration
(or importation) to the end of the current lexical scope.</p>
<p>Every macro is associated (implicitly or explicitly) with a particular
grammar rule that parses and reduces the arguments to the macro.
The formal parameters of a macro are special in that they must be
derived somehow from the results of that associated grammar rule.
We treat macros as if they were methods on the parse object returned
by the grammar rule, so the first argument is passed as if it were
an invocant, and it is always bound to the current parse tree object,
known as <code>$0</code> in Apocalypse 5.  (A macro is not a true method of that
class, however, because its name is in your scope, not the class's.)</p>
<p>[Update: That's now the <code>$/</code> object.  <code>$0</code> has been &quot;demoted&quot; to being
the first submatch.]</p>
<p>Since the first parameter is treated as an invocant, you may either
declare it or leave it implicit in the actual declaration.  In either
case, the parse tree becomes the current topic for the macro.
Hence you may refer to it as either <code>$_</code> or <code>$0</code>, even if you don't
give it a name.</p>
<p>[Update: <code>$/</code> would return the parse tree.  <code>$0</code> would only return
the first submatch.]</p>
<p>Subsequent parameters may be specified, in which case they bind to
internal values of <code>$0</code> in whatever way makes sense.  Positional
parameters bind to <code>$1</code>, <code>$2</code>, etc.  Named parameters bind to named
elements of <code>$0</code>.  A slurpy hash is really the same as <code>$0</code>, since
<code>$0</code> already behaves as a hash.  A slurpy array gets <code>$1</code>, <code>$2</code>,
etc., even if already bound to a positional parameter.</p>
<p>[Update: For <code>$0</code> read <code>$/</code> above.]</p>
<p>A macro can do anything it likes with the parse tree, but the return
value is treated specially by the parser.  You can return one of
several kinds of values:</p>
<ul>
<li><a name='A parse tree (the same one, a modified one, or a synthetic one) to be passed up to the outer grammar rule that was doing pattern matching when we hit the macro.'></a>A parse tree (the same one, a modified one, or a synthetic one) to be
passed up to the outer grammar rule that was doing pattern matching
when we hit the macro.</li>
<li><a name='A closure functioning as a generic routine that is to be immediately inlined, treating the closure as a template. Within the template, any variable referring back to one of the macro's parse parameters will interpolate that parameter's value at that point in the template. (It will be interpolated as a parse tree, a string, or a number depending on the declaration of the parameter.) Any variable not referring back to a parameter is left alone, so that your template can declare its own lexical variables, or refer to a package variable.'></a>A closure functioning as a generic routine that is to be immediately
inlined, treating the closure as a template.  Within the template, any
variable referring back to one of the macro's parse parameters will
interpolate that parameter's value at that point in the template.
(It will be interpolated as a parse tree, a string, or a number
depending on the declaration of the parameter.)  Any variable not
referring back to a parameter is left alone, so that your template
can declare its own lexical variables, or refer to a package variable.</li>
<p>[Update: instead of trying to dwim a bare closure, we now have a &quot;code&quot;
quasiquote that returns a parse tree.  See S06.]</p>
<li><a name='A string, to be shoved into the input stream and reparsed at the point the macro was found, starting in exactly the same grammar state we were before the macro. This is slightly different from returning the same string parsed into a parse tree, because a parse tree must represent a complete construct at some level, while the string could introduce a construct without terminating it. This is the most dangerous kind of return value, and the least likely to produce coherent error messages with decent line numbers for the end user. But it's also very powerful. Hee, hee.'></a>A string, to be shoved into the input stream and reparsed at the point
the macro was found, starting in exactly the same grammar state we
were before the macro.  This is slightly different from returning
the same string parsed into a parse tree, because a parse tree must
represent a complete construct at some level, while the string
could introduce a construct without terminating it.  This is the
most dangerous kind of return value, and the least likely to produce
coherent error messages with decent line numbers for the end user.
But it's also very powerful.  Hee, hee.</li>
<li><a name='An undef, indicating that the macro is only used for its side effects. Such a macro would be one way of introducing an alternate commenting mechanism, for instance. I suppose returning &quot;&quot; has the same effect, though.'></a>An <code>undef</code>, indicating that the macro is only used for its side
effects.  Such a macro would be one way of introducing an alternate
commenting mechanism, for instance.  I suppose returning &quot;&quot; has the
same effect, though.</li>
</ul>
<p>A <code>macro</code> by default parses any subsequent text using whatever
<code>macro</code> rule is currently in effect.  Generally this will be the
standard <code>Perl::macro</code> rule, which parses subsequent arguments as a
list operator would--that is, as a comma-separated list with the same
policy on using or omitting parentheses as any other list operator.
This default may be overridden with the &quot;<code>is parsed</code>&quot; trait.</p>
<p>[Update: There is probably a different default macro rule for each
syntactic category.  An infix macro wants to parse the right argument
as a single value, not a list, for instance.]</p>
<p>If there is no signature at all, <code>macro</code> defaults to using the null
rule, meaning it looks for no argument at all.  You can use it for
simple word substitutions where no argument processing is needed.
Instead of the long-winded:</p>
<pre>    my macro this () is parsed(/&lt;null&gt;/) { &quot;self&quot; }</pre>
<p>you can just quietly turn your program into C++:</p>
<pre>    my macro this { &quot;self&quot; }</pre>
<p>A lot of Perl is fun, and macros are fun, but in general, you should
never use a macro just for the fun of it.  It's far too easy to poke
someone's eye out with a macro.</p>
<a name='Out-of-band parameters'></a><h3>Out-of-band parameters</h3>
<p>Certain kinds of routines want extra parameters in addition to
the ordinary parameter list.  Autoloading routines for instance
would like to know what function the caller was trying to call.
Routines sensitive to topicalizers may wish to know what the topic
is in their caller's lexical scope.</p>
<p>There are several possible approaches.  The Perl 5 autoloader actually
pokes a package variable into the package with the <code>AUTOLOAD</code>
subroutine.  It could be argued that something that's in your dynamic
scope should be accessed via dynamically scoped variables, and indeed
we may end up with a <code>$*AUTOLOAD</code> variable in Perl 6 that works
somewhat like Perl 5's, only better, because <code>AUTOLOAD</code> kinda sucks.
We'll address that in Apocalypse 10, for some definition of &quot;we&quot;.</p>
<p>Another approach is to give access to the caller's lexical scope in
some fashion.  The magical <code>caller()</code> function could return a handle
by which you can access the caller's <code>my</code> variables.  And in general,
there will be such a facility under the hood, because we have to be
able to construct the caller's lexical scope while it's being compiled.</p>
<p>In the particular case of grabbing the topic from the caller's lexical
scope (and it has to be in the caller's <i>lexical</i> scope because <code>$_</code>
is now lexically scoped in Perl 6), we think it'll happen often enough
that there should be a shorthand for it.  Or maybe it's more like a
&quot;midhand&quot;.  We don't want it too short, or people will unthinkingly
abuse it.  Something on the order of a <code>CALLER::</code> prefix, which
we'll discuss below.</p>
<a name='Lexical context'></a><h3>Lexical context</h3>
<p>Works just like in Perl 5.  Why change something that works?</p>
<p>Well, okay, we are tweaking a few things related to lexical scopes.
<code>$_</code> (also known as the current topic) is always a lexically scoped
variable now.  In general, each subroutine will implicitly declare its
own <code>$_</code>.  Methods, submethods, macros, rules, and pointy subs all
bind their first argument to <code>$_</code>; ordinary subs declare a lexical
<code>$_</code> but leave it undefined.  Every sub definition declares its own
<code>$_</code> and hides any outer <code>$_</code>.  The only exception is bare closures
that are pretending to be ordinary blocks and don't commandeer <code>$_</code>
for a placeholder.  These continue to see the outer scope's <code>$_</code>,
just as they would any other lexically scoped variable declared in
the outer scope.</p>
<p>[Update: Methods and subs no longer bind their first argument to $_ by
default.]</p>
<a name='Dynamic context'></a><h3>Dynamic context</h3>
<p>On the flipside, <code>$_</code> is no longer visible in the dynamic context.
You can still temporize (localize) it, but you'll be temporizing
the current subroutine's lexical <code>$_</code>, not the global <code>$_</code>.
Routines which used to use dynamic scoping to view the <code>$_</code> of a calling
subroutine will need some tweaking.  See <code>CALLER::</code> below.</p>
<a name='The caller function'></a><h4>The <code>caller</code> function</h4>
<p>As in Perl 5, the <code>caller</code> function will return information about
the dynamic context of the current subroutine.  Rather than always
returning a list, it will return an object that represents the selected
caller's context.  (In a list context, the object can still return the
old list as Perl 5-ers are used to.) Since contexts are polymorphic,
different context objects might in fact supply different methods.
The <code>caller</code> function doesn't have to know anything about that,
though.</p>
<p>What <code>caller</code> does know in Perl 6 is that it takes an optional
argument. That argument says where to stop when scanning up the call
stack, and so can be used to tell <code>caller</code> which kinds of context
you're interested in.  By default, it'll skip any &quot;wrapper&quot; functions
(see &quot;The <code>.wrap</code> method&quot; below) and return the outermost context
that thought it was calling your routine directly.  Here's a possible
declaration:</p>
<pre>    multi *caller (?$where = &amp;CALLER::_, Int +$skip = 0, Str +$label)
	returns CallerContext {...}</pre>
<p>The <code>$where</code> argument can be anything that matches a particular
context, including a subroutine reference or any of these Code types:</p>
<pre>    Code Routine Block Sub Method Submethod Multi Macro Bare Parametric</pre>
<p><code>&amp;_</code> produces a reference to your current <code>Routine</code>, though in the
signature above we have to use <code>&amp;CALLER::_</code> to get at the caller's
<code>&amp;_</code>.</p>
<p>[Update: Since the caller's sub is now named <code>&amp;?ROUTINE</code>, that'd presumably
be <code>CALLER::&lt;&amp;?ROUTINE&gt;</code> instead.]</p>
<p>Note that use of <code>caller</code> can prevent certain kinds of optimizations,
such as tail recursion elimination.</p>
<a name='The want function'></a><h4>The <code>want</code> function</h4>
<p>The <code>want</code> function is really just the <code>caller</code> function in disguise.
It also takes an argument telling it which context to pay attention
to, which defaults to the one you think it should default to.  It's
declared like this:</p>
<pre>    multi *want (?$where = &amp;CALLER::_, Int +$skip = 0, Str +$label)
	returns WantContext {...}</pre>
<p>Note that, as a variant of <code>caller</code>, use of <code>want</code> can prevent
certain kinds of optimizations.</p>
<p>When <code>want</code> is called in a scalar context:</p>
<pre>	$primary_context = want;</pre>
<p>it returns a synthetic object whose type behaves as the junction of
all the valid contexts currently in effect, whose numeric overloading
returns the count of arguments expected, and whose string overloading
produces the primary context as one of 'Void', 'Scalar', or 'List'.
The boolean overloading produces true unless in a void context.</p>
<p>When <code>want</code> is called in a list context like this:</p>
<pre>	($primary, $count, @secondary) = want;</pre>
<p>it returns a list of at least two values, indicating the contexts
in which the current subroutine was called. The first two values
in the list are the primary context (i.e the scalar return value)
and the expectation count (see Expectation counts below). Any
extra contexts that <code>want</code> may detect (see Valid contexts below)
are appended to these two items.</p>
<p>When <code>want</code> is used as an object, it has methods corresponding to
its valid contexts:</p>
<pre>	if want.rw { ... }
	unless want.count &lt; 2 { ... }
	when want.List { ... }</pre>
<p>The <code>want</code> function can be used with smart matching:</p>
<pre>	if want ~~ List &amp; 2 &amp; Lvalue { ... }</pre>
<p>Which means it can also be used in a switch:</p>
<pre>    given want {
	when List &amp; 2 &amp; Lvalue { ... }
	when .count &gt; 2 {...}
    }</pre>
<p>The numeric value of the <code>want</code> object is the &quot;expectation
count&quot;. This is an integer indicating the number of return values
expected by the subroutine's caller. For void contexts, the expectation
count is always zero; for scalar contexts, it is always zero or one;
for list contexts it may be any non-negative number.  The <code>want</code>
value can simply be used as a number:</p>
<pre>    if want &gt;= 2 { return ($x, $y) }         # context wants &gt;= 2 values
    else         { return ($x); }            # context wants &lt; 2 values</pre>
<p>Note that <code>Inf &gt;= 2</code> is true.  (<code>Inf</code> is not the same as
<code>undef</code>.)  If the context is expecting an unspecified number of
return values (typically because the result is being assigned to
an array variable), the expectation count is <code>Inf</code>.  You shouldn't
actually return an infinite list, however, unless <code>want ~~ Lazy</code>.
The opposite of <code>Lazy</code> context is <code>Eager</code> context (the Perl 5 list
context, which always flattened immediately).  <code>Eager</code> and <code>Lazy</code>
are subclasses of <code>List</code>.</p>
<p>The valid contexts are pretty much as listed in RFC 21, though to the
extent that the various contexts can be considered types, they can
be specified without quotes in smart matches.  Also, types are not
all-caps any more.  We know we have a <code>Scalar</code> type--hopefully we also
get types or pseudo-types like <code>Void</code>, <code>List</code>, etc.  The <code>List</code>
type in particular is an internal type for the temporary lists that
are passed around in Perl.  Preflattened lists are <code>Eager</code>, while
those lists that are not preflattened are <code>Lazy</code>.  When you call
<code>@array.specs</code>, for instance, you actually get back an object of
type <code>Lazy</code>.  Lists (<code>Lazy</code> or otherwise) are internal
generator objects, and in general you shouldn't be doing operations
on them, but on the arrays to which they are bound.  The bound array manages its
hidden generators on your behalf to &quot;harden&quot; the abstract list into concrete
array values on demand.</p>
<p>[Update: List contexts are no longer required to keep track of how
many arguments they want.  The only meaningful values are 0, 1, and
infinity.]</p>
<a name='The CALLER:: pseudopackage'></a><h4>The <code>CALLER::</code> pseudopackage</h4>
<p>Just as the <code>SUPER::</code> pseudopackage lets you name a method somewhere
in your set of superclasses, the <code>CALLER::</code> pseudoclass lets you
name a variable that is in the lexical scope of your (dynamically
scoped) caller.  It may not be used to create a variable that does
not already exist in that lexical scope.  As such, it is is primarily
intended for a particular variable that <i>is</i> known to exist in every
caller's lexical scope, namely <code>$_</code>.  Your caller's current topic
is named <code>$CALLER::_</code>.  Your caller's current <code>Routine</code> reference
is named <code>&amp;CALLER::_</code>.</p>
<p>[Update: The latter is now <code>CALLER::&lt;&amp;?ROUTINE&gt;</code>.]</p>
<p>Note again that, as a form of <code>caller</code>, use of <code>CALLER::</code> can
prevent certain kinds of optimizations.  However, if your signature
uses <code>$CALLER::_</code> as a default value, the optimizer may be able to
deal with that as a special case.  If you say, for instance:</p>
<pre>    sub myprint (IO $handle, *@list = ($CALLER::_)) {
	print $handle: *@list;
    }</pre>
<p>then the compiler can just turn the call:</p>
<pre>    myprint($*OUT);</pre>
<p>into:</p>
<pre>    myprint($*OUT, $_);</pre>
<p>Our earlier example of <code>trim</code> might want to default the first argument
to the caller's <code>$_</code>.  In which case you can declare it as:</p>
<pre>    sub trim ( Str ?$_ is rw = $CALLER::_, Rule ?$remove = /\s+/ ) {
	    s:each/^ &lt;$remove&gt; | &lt;$remove&gt; $//;
    }</pre>
<p>which lets you call it like this:</p>
<pre>    trim;   # trims $_</pre>
<p>or even this:</p>
<pre>    trim remove =&gt; /\n+/;</pre>
<p>Do not confuse the caller's lexical scope with the <i>callee</i>'s
lexical scope.  In particular, when you put a bare block into your
program that uses <code>$_</code> like this:</p>
<pre>    for @array {
	mumble { s/foo/bar/ };
    }</pre>
<p>the compiler may not know whether or not the <code>mumble</code> routine
is intending to pass <code>$_</code> as the first argument of the closure,
which <code>mumble</code> needs to do if it's some kind of looping construct,
and doesn't need to do if it's a one-shot.  So such a bare block
actually compiles down to something like this:</p>
<pre>    for @array {
	mumble(sub ($_ is rw = $OUTER::_) { s/foo/bar/ });
    }</pre>
<p>(If you put <code>$CALLER::_</code> there instead, it would be wrong, because
that would be referring to <code>mumble</code>'s <code>$_</code>.)</p>
<p>With <code>$OUTER::_</code>, if <code>mumble</code> passes an argument to the block, that
argument becomes <code>$_</code> each time <code>mumble</code> calls the block.  Otherwise,
it's just the same outer <code>$_</code>, as if ordinary lexical scoping were
in effect.  And, indeed, if the compiler knows that <code>mumble</code> takes
a sub argument with a signature of <code>()</code>, it may optimize it down
to ordinary lexical scoping, and if it has a signature of <code>($)</code>,
it can assume it doesn't need the default.  A signature of <code>(?$)</code>
means all bets are off again.</p>
<p>[Update: the <code>CALLER::</code> mechanism has been refined into the <code>ENV::</code> variable
system.  Only variables declared with the <code>env</code> declarator are visible to
callees, but implicitly declared variables like <code>$_</code> and <code>$/</code> are included
in this category.  <code>CALLER::</code> still works the same, but <code>ENV::</code> searches
all the way up the dynamic call stack for a lexically scoped variable of that
name that has been declared with <code>env</code>.  Just as <code>$*foo</code> is shorthand for
<code>GLOBAL::&lt;$foo&gt;</code>, so too <code>$+foo</code> is shorthand for <code>ENV::&lt;$foo&gt;</code>.]</p>
<a name='Where return/leave returns to'></a><h4>Where <code>return</code>/<code>leave</code> returns to</h4>
<p>A <code>return</code> statement needs to return to where the user thinks
it ought to return to.  Since any block is a closure, any block is
really a subroutine in disguise.  But the user doesn't generally want
<code>return</code> to return from the innermost block, but from the innermost
block that was actually defined using an explicit <code>sub</code>-ish keyword.
So that's what Perl 6 does.  If it can, it will implement the <code>return</code>
internally as a simple jump to the end of the subroutine.  If it can't,
it implements <code>return</code> by throwing a control exception that is caught
by the proper context frame.</p>
<p>There will be a <code>leave</code> function that can return from other scopes.
By default it exits from the innermost block (anything matching base
class <code>Code</code>), but, as with <code>caller</code> and <code>want</code>, you can optionally
select the scope you want to return from.  It's declared like this:</p>
<pre>    multi leave (?$where = Code, *@value, Int +$skip, Str +$label) {...}</pre>
<p>which lets you say things like:</p>
<pre>    leave;
    leave Block;
    leave &amp;_ &lt;== 1,2,3;	# same as &quot;return 1,2,3&quot;
    leave where =&gt; Parametric, value =&gt; (1,2,3);
    leave Loop, label =&gt; 'LINE', $retval;
    leave { $_ ~~ Block and $_ !~ Sub } 1,2,3;
    leave () &lt;== 1,2,3;</pre>
<p>As it currently stands, the parens aren't optional on that last one,
because <code>&lt;==</code> is a binary operator.  You could always define
yourself a &quot;small&quot; return, <code>ret</code>, that leaves the innermost
block:</p>
<pre>    my macro ret { &quot;leave Code &lt;== &quot; }
    # and later...
    { ret 1,2,3 }</pre>
<p>Note that unlike a <code>return</code>, <code>leave</code> always evaluates any return
value in list context.  Another thing to iron out is that the
context we choose to leave must have set up an exception handler
that can handle the control exception that <code>leave</code> must in some
cases throw.  This seems to imply that any context must miminally
catch a control exception that is bound to its own identity, since
<code>leave</code> is doing the picking, not the exception handlers.</p>
<a name='Subroutine object methods'></a><h3>Subroutine object methods</h3>
<a name='The .wrap method'></a><h4>The <code>.wrap</code> method</h4>
<p>You may ask a subroutine to wrap itself up in another subroutine in
place, so that calls to the original are intercepted and interpreted
by the wrapper, even if access is only through the reference:</p>
<pre>    $id = $subref.wrap({
	# preprocessing here
	call;
	# postprocessing here
    })</pre>
<p>The <code>call</code> built-in knows how to call the inner function that this
function is wrapped around.  In a void context, <code>call</code> arranges for
the return value of the wrapped routine to be returned implicitly.
Alternately, you can fetch the return value yourself from <code>call</code> and
return it explicitly:</p>
<pre>    $id = $subref.wrap({
	my @retval = call;
	push(@retval, &quot;...and your little dog, too!&quot;;
	return @retval;
    })</pre>
<p>The arguments arrive in whatever form you request them, independently
of how the parameters look to the wrapped routine.  If you wish to
modify the parameters, supply a new argument list to <code>call</code>:</p>
<pre>    $id = $subref.wrap(sub (*@args) {
	call(*@args,1,2,3);
    })</pre>
<p>You need to be careful not to preflatten those generators, though.</p>
<p>[Update: Not-yet-bound arguments and return values are now represented
by a <code>Capture</code> object.]</p>
<p>The <code>$id</code> is useful for removing a particular wrapper:</p>
<pre>    $subref.unwrap($id);</pre>
<p>We might also at some point allow a built-in <code>sub</code>-like keyword
<code>wrap</code>.  If we don't, someone will write it anyway.</p>
<p>There is also likely a <code>.wrappers</code> method that represents the list
of all the current wrappers of the subroutine.  The ordering and
manipulation of this list is beyond the scope of this document, but
such activity will be necessary for anyone implementing Aspect-Oriented
Programming in Perl 6.</p>
<p>[Update: The name <code>&amp;_</code> now names the wrapped routine that <code>call</code> will
call into (which may in turn be a wrapper around some &quot;innerer&quot; routine,
but <code>&amp;_</code> points to the outermost one).  Anything that sets <code>&amp;_</code> can
use the <code>call</code> function to invoke it.]</p>
<a name='The .assuming method'></a><h4>The <code>.assuming</code> method</h4>
<p>Currying is done with the <code>.assuming</code> method.  It works a bit like
the <code>.wrap</code> method, except that instead of wrapping in place, it
returns a new function to you with a different signature, one in which
some of the parameters are assumed to be certain values:</p>
<pre>    my &amp;say ::= &amp;*print.assuming(handle =&gt; $*TERM);</pre>
<p>You can even curry built-in operators:</p>
<pre>    my &amp;prefix:½ ::= &amp;infix:/ .assuming(y =&gt; 2);</pre>
<p>(assuming here that built-in infix operators always use <code>$x</code>
and <code>$y</code>).</p>
<p>[Update: We now use hash subscript syntax for quoting:</p>
<pre>    my &amp;prefix:&lt;½&gt; ::= &amp;infix:&lt;/&gt;.assuming(y =&gt; 2);
    my &amp;prefix:{'½'} ::= &amp;infix:{'/'}.assuming(y =&gt; 2);</pre>
<p>.]</p>
<a name='The .req method'></a><h4>The <code>.req</code> method</h4>
<p>The <code>.req</code> method returns the number of required args requested
by the sub in question.  It's just a shortcut for digging down
into the <code>signature</code> trait and counting up how many required
parameters there are.  The count includes any invocant (or invocants,
for multimethods).</p>
<p>If you want to know how many optional arguments there are, you can do
your own digging.  This call is primarily for use by madmen who wish
to write variants of <code>map</code> and <code>reduce</code> that are sensitive to the
number of parameters declared for the supplied block.  (Certainly the
implementation of <code>for</code> will make heavy use of this information.)</p>
<a name='Subroutine traits'></a><h3>Subroutine traits</h3>
<p>These are traits that are declared on the subroutine as a whole,
not on any individual parameter.</p>
<a name='Internal traits'></a><h4>Internal traits</h4>
<p>The <code>signature</code>, <code>returns</code>, and <code>do</code> traits are internal traits
containing, respectively, the type signature of the parameters, the
type signature of the return value, and the body of the function.
Saying:</p>
<pre>    sub Num foo (int $one, Str *@many) { return +@many[$one] }</pre>
<p>is short for saying something like:</p>
<pre>    sub foo is signature( sig(int $one, Str *@many) )
	    is returns( sig(Num) )
	    will do { return +@many[$one] }</pre>
<p>In fact, it's likely that the &quot;do&quot; trait handler has to set up all
the linkage to pass parameters in and to trap &quot;return&quot; exceptions.</p>
<p>Many of these pre-defined traits just map straight onto the container
object's attribute methods of the same name.  Underneath they're just
accessors, but we use the trait notation in declarations for several
reasons.  For one thing, you can string a bunch of them together
without repeating the original object, which might be anonymous in
any event.  It also gives us liberty behind the scenes to promote
or demote various traits from mere properties to attributes of every
object of a class.  It's one of those levels of indirection computer
scientists keep talking about...</p>
<p>Going the other direction, it allows us to pretend that accessors are
just another form of metadata when accessed as a trait.  By the same
token it allows us to transparently make our metadata active rather
than passive, without rewriting our declarations.  This seems useful.</p>
<p>The basic rule of thumb is that you can use any of a container's
<code>rw</code> methods as if it were a trait.  For subroutine containers,
the example above really turns into something like this:</p>
<pre>    BEGIN {
	&amp;foo.signature = sig(int $one, Str *@many);
	&amp;foo.returns = sig(Num);
	&amp;foo.do = { return +@many[$one] }
    }</pre>
<p>[Update: A12 goes as far as to turn all properties (including traits)
into mixins, so all these traits really are accessor methods.]</p>
<a name='is rw'></a><h4><code>is rw</code></h4>
<p>This trait identifies lvalue subs or methods.  See the section on
lvalue subs below.</p>
<a name='is parsed(&lt;rule&gt;)'></a><h4><code>is parsed(<i>&lt;rule&gt;</i>)</code></h4>
<p>This trait binds a macro to a grammar rule for parsing it.  The grammar
rule is invoked as soon as the initial keyword is seen and before
anything else is parsed, so you can completely change the grammar on
the fly.  For example, the <code>sig()</code> function above might well invoke
special parsing rules on its arguments, since what is inside is not
an ordinary expression.</p>
<p>In the absence of an explicit &lt;is parsed&gt; trait, a macro's arguments
are parsed with whatever <code>macro</code> rule is in effect, by default the
standard <code>Perl::macro</code>.</p>
<p>[Update: The default parse rule probably turns out to be dependent on
the grammatical category of the macro.  A prefix macro wants a list by
default, while an infix macro just wants a scalar expression for the
right argument.  A term probably wants no argument at all.  Macros for
things like rule modifiers probably want to parse like trait verbs.
On the other hand, an infix_circumfix_meta_operator like <code>» «</code>
just wants to recognize certain strings inside that also happen to
be valid infix operators.]</p>
<a name='is cloned(&quot;BEGIN&quot;)'></a><h4><code>is cloned(&quot;BEGIN&quot;)</code></h4>
<p>Perhaps this is an alternate way of specifying the parsing and
semantics of a macro or function.  Or perhaps not.  Just an idea
for now...</p>
<a name='is cached'></a><h4><code>is cached</code></h4>
<p>This is the English translation of what some otherwise sane folks call
&quot;memoization&quot;.  This trait asserts that Perl can do automatic caching
of return values based on the assumption that, for any particular set
of arguments, the return value is always the same.  It can dramatically
speed up certain kinds of recursive functions that shouldn't have
been written recursively in the first place.  <code>;-)</code></p>
<a name='is inline'></a><h4><code>is inline</code></h4>
<p>This says you think performance would be enhanced if the code were
inlined into the calling code.  Of course, it also constitutes a
promise that you're not intending to redefine it or wrap it or do
almost anything else fancy with it, such as expecting it to get
called by a method dispatcher.  In early versions of Perl 6, it's
likely to be completely ignored, I suspect.  (If not, it's likely to
be completely broken...)</p>
<a name='PRE/POST/FIRST/LAST/etc.'></a><h4><code>PRE</code>/<code>POST</code>/<code>FIRST</code>/<code>LAST</code>/etc.</h4>
<p>These all-caps traits are generally set from the inside of a
subroutine as special blocks.  <code>FIRST</code> and <code>LAST</code> are expected
to have side effects.  <code>PRE</code> and <code>POST</code> are expected to not have
side effects, but return a boolean value indicating whether pre/post
conditions have been met.  If you declare any <code>PRE</code> or <code>POST</code> conditions,
your routine will automatically be wrapped in a wrapper that evaluates
them according to Design-by-Contract principles (ORing preconditions,
ANDing postconditions).</p>
<p>Note that the actual &quot;first&quot; or &quot;last&quot; property attached to a
subroutine may well be a list of <code>FIRST</code> or <code>LAST</code> blocks, since
there can be more than one of them.</p>
<p>[Update: <code>FIRST</code> and <code>LAST</code> are now named <code>ENTER</code> and <code>LEAVE</code>.
There is still a <code>FIRST</code> block, but it has different semantics
from <code>ENTER</code>--an <code>ENTER</code> fires every time this block is entered,
but a <code>FIRST</code> will only fire the first time the block is entered,
and not on subsequent entries.  (If a closure is cloned, each clone
is considered a separate block for initialization purposes, since
each closure clone gets its own copies of any state variables, and
the <code>FIRST</code> block is primarily for initializing state variables.
The &quot;firstness&quot; may be implicit: assignment to a <code>state</code> variable
declaration implies &quot;first&quot; semantics, just as assignment to an
object attribute declaration implies attribute defaults at &quot;build&quot;
time, not real assignment.)]</p>
<a name='Overriding built-ins'></a><h3>Overriding built-ins</h3>
<p>All built-in functions that can be overridden are either multimethods
or global subroutines.  To override one of these, just declare your
own subroutine of that name in your current package or lexical scope.
For instance, the standard non-filehandle print function may well be
declared as:</p>
<pre>    multi *print (*@list) {...}</pre>
<p>Just declare your own sub:</p>
<pre>    sub print (*@list) {...}</pre>
<p>to override all <code>print</code> multimethods in the current package, or:</p>
<pre>    my sub print (*@list) {...}</pre>
<p>to override in the current lexical scope.</p>
<p>To override or wrap a built-in function for everyone (dangerous),
you have to play with the globally named version, but we're not going
to tell you how to do that.  If you can't figure it out, you
shouldn't be doing it.</p>
<a name='Subs with special parsing'></a><h3>Subs with special parsing</h3>
<p>Any macro can have special parsing rules if you use the <code>is parsed</code>
trait.  But some subs are automatically treated specially.</p>
<a name='Operator subroutines'></a><h4>Operator subroutines</h4>
<p>In Perl 6, operators are just subroutines with special names.  When you
say:</p>
<pre>    -$a + $b</pre>
<p>you're really doing this internally:</p>
<pre>    infix:+( prefix:-($a), $b)</pre>
<p>[Update: That's now</p>
<pre>    infix:&lt;+&gt;( prefix:-($a), $b)</pre>
<p>.]</p>
<p>Operator names start with one of four names followed by a colon:</p>
<pre>    prefix:	a unary prefix operator
    infix:	a binary infix operator
    postfix:	a unary suffix operator
    circumfix:	a bracketing operator</pre>
<p>Everything after the colon and up to the next whitespace or left
parenthesis will be taken as the spelling of the actual operator.
Unicode is specifically allowed.  The null operator is not allowed,
so if the first thing after the colon is a left parenthesis, it
is part of the operator, and if the first thing is whitespace,
it's an illegal name.  Boom!</p>
<p>[Update: Nowadays the operator name is quoted as if it were a hash
subscript.  A null name specifies a default rule to match when that
syntactic category is in effect, but nothing else matches.]</p>
<p>You can make your own lexically scoped operators like this:</p>
<pre>    my sub postfix:! (Int $x) { return factorial($x) }
    print 5!, &quot;\n&quot;;	# print 120</pre>
<p>[Update: That's <code>postfix:&lt;!&gt;</code> now.]</p>
<p>You can use a newly declared operator recursively as soon as its name
is introduced, including in its own definition:</p>
<pre>    my sub postfix:! (Int $x) { $x&lt;=1 ?? 1 :: $x*($x-1)! }</pre>
<p>You can declare multimethods that create new syntax like this:</p>
<pre>    multi postfix:! (Int $x) { $x&lt;=1 ?? 1 :: $x*($x-1)! }</pre>
<p>However, regardless of the scope of the name, the new <i>syntax</i> is
considered to be a lexically scoped declaration, and is only valid
after the name is declared (or imported) and after any precedence
traits have been parsed.</p>
<p>If you want to specify a precedence, you always do it relative to
some existing operator:</p>
<pre>    multi infix:coddle   (PDL $a, PDL $b) is equiv(&amp;infix:+) { ... }
    multi infix:poach    (PDL $a, PDL $b) is looser(&amp;infix:+) { ... }
    multi infix:scramble (PDL $a, PDL $b) is tighter(&amp;infix:+) { ... }</pre>
<p>[Update: Now <code>infix:&lt;coddle&gt;</code> etc.]</p>
<p>If you base a tighter operator on a looser one, or a looser one on
a tighter one, you don't get back to where you were.  It always goes
into the cracks no matter how many times you derive.</p>
<p>Just a note on implementation: if you've played with numerically
oriented precedence tables in the past, and are thinking, &quot;but he'll
run out of bits in his number eventually.&quot;  The answer to that is that
we don't use precedence numbers.  The actual precedence level can be
represented internally by an arbitrarily long string of bytes that are
compared byte by byte.  When you make a tighter or looser operator,
the string just gets one byte longer.  A looser looser looser looser
<code>infix:*</code> is still tighter than a tighter tighter tighter tighter
<code>infix:+</code>, because the string comparison bails out on the first byte.
The first byte compares the built-in multiplication operator against
the built-in addition operator, and those are already different,
so we don't have to compare any more.</p>
<p>However, two operators derived by the same path have the same
precedence.  All binary operators of a given precedence level are
assumed to be left associative unless declared otherwise with an
<code>assoc('right')</code> or <code>assoc('non')</code> trait.  (Unaries pay no attention
to associativity--they always go from the outside in.)</p>
<p>This may sound complicated, and it is, if you're implementing
it internally.  But from the user's point of view, it's much less
complicated than trying to keep track of numeric precedence levels
yourself.  By making the precedence levels relative to existing
operators, we keep the user from having to think about how to keep
those cracks open.  And most user-defined operators will have exactly
the same precedence as something built-in anyway.  Not to mention the
fact that it's just plain better documentation to say that an operator
works like a familiar operator such as &quot;<code>+</code>&quot;.  Who the heck can
remember what precedence level 17 is, anyway?</p>
<p>If you don't specify a precedence on an operator, it will default
to something reasonable.  A named unary operator, whether prefix or
postfix, will default to the same precedence as other named unary
operators like <code>abs()</code>.  Symbolic unaries default to the same
precedence as unary <code>+</code> or <code>-</code> (hence the <code>!</code> in our factorial
example is tighter than the <code>*</code> of multiplication.)  Binaries default
to the same precedence as binary <code>+</code> or <code>-</code>.  So in our <code>coddle</code>
example above, the <code>is equiv(&amp;infix::+)</code> is completely redundant.</p>
<p>Unless it's completely wrong.  For multimethods, it's an error to
specify two different precedences for the same name.  Multimethods that
overload an existing name will be assumed to have the same precedence
as the existing name.</p>
<p>You'll note that the rules for the scope of syntax warping are similar
to those for macros.  In essence, these definitions are macros,
but specialized ones.  If you declare one as a macro, the body is
executed at compile time, and returns a string, a parse tree, or a
closure just as a macro would:</p>
<pre>    # define Pascal comments:
    macro circumfix:&lt;(* *)&gt; () is parsed(/.*?/) { &quot;&quot; }
				# &quot;Comment? What comment?&quot;</pre>
<p>A circumfix operator is assumed to be split symmetrically between
prefix and postfix.  In this case the circumfix of four characters
is split exactly in two, but if you don't want it split in the
middle (which is particularly gruesome when there's an odd number
of characters) you may specify exactly where the parse rule is
interpolated with a special <code> ... </code> marker, which is considered part
of the name:</p>
<pre>    macro circumfix:(*...*) () is parsed(/.*?/) { &quot;&quot; }</pre>
<p>[Update: That's now solved by use of existing slice syntax:</p>
<pre>    macro circumfix:&lt;(* *)&gt; () is parsed(/.*?/) { &quot;&quot; }
    macro circumfix:{'(*', '*)'} () is parsed(/.*?/) { &quot;&quot; }</pre>
<p>That's so convenient that we'll discard the special rule about
splitting symmetrically in favor of requiring a two element slice.]</p>
<p>The default parse rule for a circumfix is an ordinary Perl expression of
lowest precedence, the same one Perl uses inside ordinary parentheses.
The defaults for other kinds of operators depend on the precedence of
the operator, which may or may not be reflected in the actual name of
the grammatical rule.</p>
<p>[Update: It depends not on the precedence but on the grammatical
category.]</p>
<p>Note that the ternary operator <code>??::</code> has to be parsed as an infix
<code>??</code> operator with a special parsing rule to find the associated
<code>::</code> part.  I'm not gonna explain that here, partly because
user-defined ternary operators are discouraged, and partly because
I haven't actually bothered to figure out the details yet.  This
Apocalypse is already late enough.</p>
<p>[Update: Ternary operator is now <code>??!!</code>, actually...]</p>
<p>Also please note that it's perfectly permissible (but not extremely
expeditious) to rapidly reduce the Perl grammar to a steaming pile
of gopher guts by redefining built-in operators such as commas or
parentheses.</p>
<a name='Named unaries'></a><h4>Named unaries</h4>
<p>As in Perl 5, a named unary operator by default parses with the
same precedence as all other named unary operators like <code>sleep</code>
and <code>rand</code>.  Any sub declared with a single scalar argument counts
as a named unary, not just explicit operator definitions.  So it
doesn't really matter whether you say:</p>
<pre>    sub plaster ($x) {...}</pre>
<p>or:</p>
<pre>    sub prefix:plaster ($x) {...}</pre>
<a name='Argumentless subs'></a><h4>Argumentless subs</h4>
<p>As in Perl 5, a 0-ary subroutine (one with a <code>()</code> signature) parses
without looking for any argument at all, much like the <code>time</code>
built-in.  (An optional pair of empty parens are allowed on the call,
as in <code>time()</code>.)  Constant subs with a null signature will likely
be inlined as they are in Perl 5, though the preferred way to declare
constants will be as standard variables with the <code>is constant</code> trait.</p>
<a name='Matching of forward declarations'></a><h3>Matching of forward declarations</h3>
<p>If you define a subroutine for which you earlier had a stub
declaration, its signature and traits must match the stub's subroutine
signature and traits, or it will be considered to be declaring a
different subroutine of the same name, which may be any of illegal,
immoral, or fattening.  In the case of standard subs, it would be
illegal, but in the case of multimethods, it would merely be fattening.
(Well, you'd also get a warning if you called the stub instead of the
&quot;real&quot; definition.)</p>
<p>The declaration and the definition should have the same defaults.  That
does not just mean that they should merely <i>look</i> the same.  If you say:</p>
<pre>    our $x = 1;
    sub foo ($y = $x) {...}		# default to package var

    {
	my $x = 2;
	sub foo ($y = $x) { print $y }	# default to lexical var
	foo();
    }</pre>
<p>then what you've said is an error if the compiler can catch it, and
is erroneous if it can't.  In any event, the program may correctly
print any of these values:</p>
<pre>    1
    2
    1.5
    12
    1|2
    (1,2)
    Thbthbthbthth...
    1|2|1.5|12|(1|2)|(1,2)|Thbthbthbthth...</pre>
<a name='Lvalue subroutines'></a><h3>Lvalue subroutines</h3>
<p>The purpose of an lvalue subroutine is to return a &quot;proxy&quot;--that is,
to return an object that represents a &quot;single evaluation&quot; of the
subroutine while actually allowing multiple accesses within a single
transaction.  An lvalue subroutine has to pretend to be a storage
location, with all the rights, privileges, and responsibilities
pertaining thereto.  But it has to do this without repeatedly
calculating the <i>identity</i> of whatever it is you're actually modifying
underneath--especially if that calculation entails side effects.
(Or is expensive--meaning that it has the side-effect of chewing up
computer resources...)</p>
<p>An lvalue subroutine is declared with the <code>is rw</code> trait.  The compiler
will take whatever steps necessary to ensure that the returned value
references a storage location that can be treated as an lvalue.
If you merely return a variable (such as an object attribute), that
variable can act as its own proxy.  You can also return the result
of a call to another lvalue subroutine or method.  If you need to do
pre- or post-processing on the &quot;public&quot; value, however, you'll need
to return a tied proxy variable.</p>
<p>But if you know how hard it is to tie variables in Perl 5, you'll be
pleasantly surprised that we're providing some syntactic relief for the
common cases.  In particular, you can say something like:</p>
<pre>    my sub thingie is rw {
	return my $var
	    is Proxy( for =&gt; $hidden_var,
		      FETCH =&gt; { ... },
		      STORE =&gt; { ... },
		      TEMP  =&gt; { ... },
		      ...
	    );
    }</pre>
<p>in order to generate a tie class on the fly, and only override the
standard proxy methods you need to, while letting others default to
doing the standard behavior.  This is particularly important when
proxying things like arrays and hashes that have oodles of potential
service routines.</p>
<p>But in particular, note that we want to be able to temporize object
attributes, which is why there's a <code>TEMP</code> method in our proxy.  In Perl 5
you could only temporize (localize) variables.  But we want accessors
to be usable exactly as if they were variables, which implies that
temporization is part of the interface.  When you use a <code>temp</code>
or <code>let</code> context specifier:</p>
<pre>    temp $obj.foo = 42;
    let $obj.bar = 43;</pre>
<p>the proxy attribute returned by the lvalue method needs to know how to
temporize the value.  More precisely, it needs to know how to restore
the old value at the end of the dynamic scope.  So what the <code>.TEMP</code>
method returns is a closure that knows how to restore the old value.
As a closure, it can simply keep the old value in a lexical created
by <code>.TEMP</code>.  The same method is called for both <code>temp</code> and <code>let</code>.
The only difference is that <code>temp</code> executes the returned closure
unconditionally at end of scope, while <code>let</code> executes the closure
conditionally only upon failure (where failure is defined as throwing
a non-control exception or returning undef in scalar context or <code>()</code>
in list context).</p>
<p>[Update: Returning () is now considered successful.  An undef may now
be returned in a list context to indicate failure, and it acts as a
generator of 0 elements if you force list flattening.  Use <code>scalar
undef</code> to actually interpolate a single undef value in a list.]</p>
<p>After the <code>.TEMP</code> method returns the closure, you never have to worry
about it again.  The <code>temp</code> or <code>let</code> will squirrel away the closure
and execute it later when appropriate.  That's where the real power of
<code>temp</code> and <code>let</code> comes from--they're fire-and-forget operators.</p>
<p>The standard <code>Scalar</code>, <code>Array</code>, and <code>Hash</code> classes also have
a <code>.TEMP</code> method (or equivalent). So <i>any</i> such variable can be
temporized, even lexicals:</p>
<pre>    my $identity = 'Clark Kent';

    for @emergencies {
	 temp $identity = 'SUPERMAN';   # still the lexical $identity
	 ...
    }

    print $identity;    # prints 'Clark Kent'</pre>
<p>We'll talk more about lvalues below in reference to various RFCs that
espouse lvalue subs--all of which were rejected. <code>:-)</code></p>
<a name='Temporizing any subroutine call'></a><h3>Temporizing any subroutine call</h3>
<p>Lvalue subroutines have a special way to return a proxy that can be
temporized, but sometimes that's overkill.  Maybe you don't want an
lvalue; you just want a subroutine that can do something temporarily
in an rvalue context.  To do that, you can declare a subroutine with
a <code>TEMP</code> block that works just like the <code>.TEMP</code> method described
earlier.  The <code>TEMP</code> block returns a closure that will be called
when the <i>call</i> to this function goes out of scope.</p>
<p>So if you declare a function with a <code>TEMP</code> property:</p>
<pre>    sub setdefout ($x) {
	my $oldout = $*OUT;
	$*DEFOUT = $x;
	TEMP {{ $*DEFOUT = $oldout }}
    }</pre>
<p>then you can call it like this:</p>
<pre>    temp setdefout($MYFILE);</pre>
<p>and it will automatically undo itself on scope exit.  One place where
this might be useful is for wrappers:</p>
<pre>    temp &amp;foo.wrap({...})</pre>
<p>The routine will automatically unwrap itself at the end of the current
dynamic scope.  A <code>let</code> would similarly put a hypothetical wrapper
in place, but keep it wrapped on success.</p>
<p>The <code>TEMP</code> block is called only if you invoke the subroutine or method
with <code>temp</code> or <code>let</code>.  Otherwise the <code>TEMP</code> block is ignored.  So if
you just call:</p>
<pre>    setdefout($MYFILE);</pre>
<p>then the side-effects are permanent.</p>
<p>That being said...</p>
<p>I don't think we'll actually be using explicit <code>TEMP</code> closures all
over the place, because I'd like to extend the semantics of <code>temp</code>
and <code>let</code> such that they automatically save state of anything within
their dynamic scopes.  In essence, Perl writes most of the <code>TEMP</code>
methods for you, and you don't have to worry about them unless you're
interfacing to external code or data that doesn't know how to save
its own state.  (Though there's certainly plenty of all that out
in the wide world.)</p>
<p>See appendix C for more about this line of thought.</p>
<a name='The RFCs'></a><h2>The RFCs</h2>
<p>Let me reiterate that there's little difference between an RFC accepted
with major caveats and a rejected RFC from which some ideas may have
been stolen.  Please don't take any of this personally--I ignore
author names when evaluating RFCs.</p>
<a name='Rejected RFCs'></a><h3>Rejected RFCs</h3>
<a name='RFC 59: Proposal to utilize * as the prefix to magic subroutines'></a><h4>RFC 59: Proposal to utilize <code>*</code> as the prefix to magic
subroutines</h4>
<p>There are several problems with doing this.</p>
<ul>
<li><a name='The * prefix is already taken for two other meanings. (It indicates a completely global symbol or a splatlist.) We could come up with something else, but we're running out of keyboard. And I don't think it's important enough to inflict a Unicode character on people.'></a>The <code>*</code> prefix is already taken for two other meanings.  (It indicates
a completely global symbol or a splatlist.)  We could come up with
something else, but we're running out of keyboard.  And I don't think
it's important enough to inflict a Unicode character on people.</li>
<li><a name='It would be extra clutter that conveys little extra information over what is already conveyed by all-caps.'></a>It would be extra clutter that conveys little extra information
over what is already conveyed by all-caps.</li>
<li><a name='All-caps routines are a fuzzy set. Some of these routines are always called implicitly, while others are only usually called implicitly. We'd have to be continually making arbitrary decisions on where to cut it off.'></a>All-caps routines are a fuzzy set.  Some of these routines are
always called implicitly, while others are only <i>usually</i> called
implicitly.  We'd have to be continually making arbitrary decisions
on where to cut it off.</li>
<li><a name='Some routines are in the process of migrating into (or out of) the core. We don't want to force people to rewrite their programs when that happens.'></a>Some routines are in the process of migrating into (or out of)
the core.  We don't want to force people to rewrite their programs
when that happens.</li>
<li><a name='People are already used to the all-caps convention.'></a>People are already used to the all-caps convention.</li>
<li><a name='Most importantly, I have an irrational dislike for anything that resembles Python's __foo__ convention. :-)'></a>Most importantly, I have an irrational dislike for anything that
resembles Python's <code>__foo__</code> convention.  <code>:-)</code></li>
</ul>
<p>So we'll continue to half-heartedly reserve the all-caps space for
Perl magic.</p>
<a name='RFC 75: structures and interface definitions'></a><h4>RFC 75: structures and interface definitions</h4>
<p>In essence, this proposal turns every subroutine call into a
constructor of a parameter list object.  That's an interesting way to
look at it, but the proposed notation for class declaration suffers
from some problems.  It's run-time rather than compile-time, and
it's based on a value list rather than a statement list.  In other
words, it's not what we're gonna do, because we'll have a more
standard-looking way of declaring classes.  (On the other hand, I
think the proposed functionality can probably be modeled by suitable
use of constructors.)</p>
<p>The proposal also runs afoul of the rule that a lexically scoped
variable ought generally to be declared explicitly at the beginning
of its lexical scope.  The parameters to subroutines will be lexically
scoped in Perl 6, so there needs to be something equivalent to a <code>my</code>
declaration at the beginning.</p>
<p>Unifying parameter passing with <code>pack</code>/<code>unpack</code> syntax is, I
think, a false economy.  <code>pack</code> and <code>unpack</code> are serialization
operators, while parameter lists are about providing useful aliases
to caller-provided data without any implied operation.  The fact that
both deal with lists of values on some level doesn't mean we should
strain to make them the same on every level.  That will merely make
it impossible to implement subroutine calls efficiently, particularly
since the Parrot engine is register-based, not stack-based as this
RFC assumes.  Register-based machines don't access parameters by
offsets from the stack pointer.</p>
<a name='RFC 107: lvalue subs should receive the rvalue as an argument'></a><h4>RFC 107: lvalue subs should receive the rvalue as an argument</h4>
<p>This would make it hard to dynamically scope an attribute.  You'd have
to call the method twice--once to get the old value, and once to set
the new value.</p>
<p>The essence of the lvalue problem is that you'd like to separate
the identification of the object from its manipulation.  Forcing
the new value into the same argument list as arguments meant to
identify the object is going to mess up all sorts of things like
assignment operators and temporization.</p>
<a name='RFC 118: lvalue subs: parameters, explicit assignment, and wantarray() changes'></a><h4>RFC 118: lvalue subs: parameters, explicit assignment, and
wantarray() changes</h4>
<p>This proposal has a similar problem in that it doesn't separate
the identity from the operation.</p>
<a name='RFC 132: Subroutines should be able to return an lvalue'></a><h4>RFC 132: Subroutines should be able to return an lvalue</h4>
<p>This RFC proposes a keyword <code>lreturn</code> to return an lvalue.</p>
<p>I'd rather the lvalue hint be available to the compiler, I think, even
if the body has not been compiled yet.  So it needs to be declared
in the signature somehow.  The compiler would like to know whether
it's even legal to assign to the subroutine.  Plus it might have to
deal with the returned value as a different sort of object.</p>
<p>At least this proposal doesn't confuse identification with
modification.  The lvalue is presumably an object with a <code>STORE</code>
method that works independently of the original arguments.  But this
proposal also doesn't provide any mechanism to do postprocessing on
the stored value.</p>
<a name='RFC 149: Lvalue subroutines: implicit and explicit assignment'></a><h4>RFC 149: Lvalue subroutines: implicit and explicit assignment</h4>
<p>This is sort of the don't-have-your-cake-and-don't-eat-it-too
approach.  The implicit assignment doesn't allow for virtual
attributes.  The explicit assignment doesn't allow for delayed
modification.</p>
<a name='RFC 154: Simple assignment lvalue subs should be on by default'></a><h4>RFC 154: Simple assignment lvalue subs should be on by default</h4>
<p>Differentiating &quot;simple&quot; lvalue subs is a problem.  A user ought to
just be able to say something fancy like</p>
<pre>    temp $obj.attr += 3;</pre>
<p>and have it behave right, provided <code>.attr</code> allows that.</p>
<p>Even with:</p>
<pre>    $obj.attr = 3;</pre>
<p>we have a real problem with knowing what can be done at compile time,
since we might not know the exact type of <code>$obj</code>.  Even if <code>$obj</code>
is declared with a type, it's only an &quot;isa&quot; assertion.  We could
enforce things based on the declared type with the assumption that a
derived type won't violate the contract, but I'm a little worried about
large semantic changes happening just because one adds an optional
type declaration.  It seems safer that the untyped method behave
just like the typed method, only with run-time resolution rather than
compile-time resolution.  Anything else would violate the principle of
least surprise.  So if it is not known whether <code>$obj.attr</code> can be an
lvalue, it must be assumed that it can, and compiled with a mechanism
that will work consistently, or throw a run-time exception if it can't.</p>
<p>The same goes for argument lists, actually.  <code>$obj.meth(@foo)</code>
can't assume that <code>@foo</code> is either scalar or list until it knows the
signature of the <code>.meth</code> method.  And it probably doesn't know that
until dispatch time, unless it can analyze the entire set of available
methods in advance.  In general, modification of an invalid lvalue
(an object without a write method, essentially) has to be handled by
throwing an exception.  This may well mean that it is illegal for a
method to have an <code>rw</code> parameter!</p>
<p>Despite the fact that there are similar constraints on the arguments
and on the lvalue, we cannot combine them, because the values are
needed at different times.  The arguments are needed when identifying
the object to modify, since lvalue objects often act as proxies for
other objects elsewhere.  Think of subscripting an array, for instance,
where the subscripts function as arguments, so you can say:</p>
<pre>    $elem := @a[0][1][2];
    $elem = 3;</pre>
<p>Likewise we should be able to say:</p>
<pre>    $ref := a(0,1,2);
    $ref = 3;</pre>
<p>and have <code>$ref</code> be the lvalue returned by <code>a()</code>.  It's the implied
&quot;<code>is rw</code>&quot; on the left that causes <code>a()</code> to return an lvalue, just
as a subroutine parameter that is &quot;<code>rw</code>&quot; causes lvaluehood to be
passed to its actual argument.</p>
<p>Since we can't in general know at compile time whether a method is
&quot;simple&quot; or not, we don't know whether it's appropriate to treat
an assignment as an extra argument or as a parameter to an internal
<code>STORE</code> method.  We have to compile the call assuming there's a separate
<code>STORE</code> method on the lvalue object.  Which means there's no such thing
as a &quot;simple&quot; lvalue from the viewpoint of the caller.</p>
<a name='Accepted RFCs'></a><h3>Accepted RFCs</h3>
<a name='RFC 168: Built-in functions should be functions'></a><h4>RFC 168: Built-in functions should be functions</h4>
<p>This all seems fine to me in principle.  All built-in functions and
multimethods exist in the &quot;<code>*</code>&quot; space, so <code>system()</code> is really
<code>&amp;*system();</code> in Perl 6 .</p>
<p>We do need to consider whether &quot;<code>sub system</code>&quot; changes the meaning
of calls to <code>system()</code> earlier in the lexical scope.  Or are
built-ins imported as third-class keywords like <code>lock()</code> is in
Perl 5?  It's probably best if we detect the ambiguous situation and
complain.  A &quot;late&quot; definition of <code>system()</code> could be considered
a redefinition, in fact, any definition of <code>system()</code> could be
considered a redefinition.  We could require &quot;<code>is redefined</code>&quot; or
some such on all such redefinitions.</p>
<p>[Update: &quot;<code>is instead</code>&quot; is the currently approved incantation.]</p>
<p>The &quot;<code>lock</code>&quot; situation arises when we add a new built-in, however.
Do we want to force people to add in an &quot;<code>is redefined</code>&quot; where they
didn't have to before?  Worse, if their definition of &quot;<code>lock</code>&quot; is
retroactive to the front of the file, merely adding &quot;<code>sub lock is
redefined</code>&quot; is not necessarily good enough to become retroactive.</p>
<p>This is not a problem with <code>my</code> subs, since they have to be declared
in advance.  If we defer committing compilation of package-named
subs to the end of the compilation unit, then we can just say that
the current package overrides the &quot;<code>*</code>&quot; package.  All built-ins
become &quot;third class&quot; keywords in that case.  But does that mean
that a built-in can't override ordinary function-call syntax?
Built-ins should at least be able to be used as list operators, but
in Perl 5 you couldn't use your own sub as a list operator unless it
was predeclared.  Maybe we could relax that.</p>
<p>Since there are no longer any barewords, we can assume that any
unrecognized word is a subroutine or method call of some sort even
in the absence of parens.  We could assume all such words are list
operators.  That works okay for overriding built-ins that actually
*are* list operators--but not all of them are.  If you say:</p>
<pre>    print rand 1, 2;
    sub rand (*@x) { ... }</pre>
<p>then it cannot be determined whether <code>rand</code> should be parsed as a
unary operator <code>($)</code> or as a list operator <code>(*@)</code>.</p>
<p>Perl has to be able to parse its unary operators.  So that code
must be interpreted as:</p>
<pre>    print rand(1), 2;</pre>
<p>At that point in the parse, we've essentially committed to a signature
of <code>($)</code>, which makes the subsequent sub declaration a redefinition
with a different signature, which is illegal.  But when someone says:</p>
<pre>    print foo 1, 2;
    sub foo (*@x) { ... }</pre>
<p>it's legal until someone defines <code>&amp;*foo($)</code>.  We can protect ourselves
from the backward compatibility problem by use of parens.  When there
are parens, we can probably defer the decision about the binding of
its arguments to the end of the compilation.  So either of:</p>
<pre>    print foo(1), 2;
    sub foo (*@x) { ... }</pre>
<p>or:</p>
<pre>    print foo(1, 2);
    sub foo (*@x) { ... }</pre>
<p>remain legal even if we later add a unary <code>&amp;*foo</code> operator, as long as
no other syntactic monkey business is going on with the functions args.
So I think we keep the rule that says post-declared subs have to be
called using parens, even though we could theoretically relax it.</p>
<p>On the other hand, this means that any unrecognized word followed by
a list may unambiguously be taken to be a multimethod being called
as a list operator.  After all, we don't know when someone will be
adding more multimethods.  I currently think this is a feature, but
I could be sadly mistaken.  It has happened once or twice in the past.</p>
<p>[Update: Post-declared subs are now always assumed to parse the same as
as listops.]</p>
<a name='RFC 57: Subroutine prototypes and parameters'></a><h4>RFC 57: Subroutine prototypes and parameters</h4>
<p>We ended up with something like this proposal, though with some
differences.  Instead of <code>=</code>, we're using <code>=&gt;</code> to specify
names because it's a pair constructor in Perl 6, so there's little
ambiguity with positional parameters.  Unless a positional parameter
is explicitly declared with a <code>Pair</code> or <code>Hash</code> type, it's assumed
not to be interested in named arguments.</p>
<p>Also, as the RFC points out, use of <code>=</code> would be incompatible with
lvalue subs, which we're supporting.</p>
<p>[Update: we now recognize the <code>:ident($arg)</code> and <code>ident =&gt; $arg</code>
forms as named parameters, and other uses of <code>=&gt;</code> are assumed
to be pair constructors.]</p>
<p>The RFC allows for mixing of positional and named parameters, both
in declaration and in invocation.  I think such a feature would
provide far more confusion than functionality, so we won't allow it.
You can always process your own argument list if you want to.  You
could even install your own signature handler in place of Perl's.</p>
<p>[Update: we now allow it, but discourage it.]</p>
<p>The RFC suggests treating the first parameter with a default as the
first optional parameter.  I think I'd rather mark optional parameters
explicitly, and then disallow defaults on required parameters as
a semantic constraint.</p>
<p>It's also suggested that something like:</p>
<pre>    sub waz ($one, $two, 
	     $three = add($one, $two), 
	     $four  = add($three, 1)) {
	...
    }</pre>
<p>be allowed, where defaults can refer back to previous parameters.
It seems as though we could allow that, if we assume that symbols
are introduced in signatures as soon as they are seen.  That would
be consistent with how we've said <code>my</code> variables are introduced.
It does mean that a prototype that defaults to the prior <code>$_</code> would
have to be written like this:</p>
<pre>    $myclosure = sub ($_ = $OUTER::_) { ... }</pre>
<p>On the other hand, that's exactly what:</p>
<pre>    $myclosure = { ... }</pre>
<p>means in the absence of placeholder variables, so the situation will
likely not arise all that often.  So I'd say yes, defaults should
be able to refer back to previous parameters in the same signature,
unless someone thinks of a good reason not to.</p>
<p>As explained in Apocalypse 4, <code>$OUTER::</code> is for getting at an outer
lexical scope.  This ruling about formal parameters means that,
effectively, the lexical scope of a subroutine &quot;starts to begin&quot;
where the formal parameters are declared, and &quot;finishes beginning&quot; at
the opening brace.  Whether a given symbol in the signature actually
belongs to the inner scope or the outer scope depends on whether it's
already been introduced by the inner scope.  Our sub above needed
<code>$OUTER::_</code> because <code>$_</code> had already been introduced as the name
of the first argument.  Had some other name been introduced, <code>$_</code>
might still be taken to refer to the outer <code>$_</code>:</p>
<pre>    $myclosure = sub ($arg = $_) { ... }</pre>
<p>If so, use of <code>$OUTER::_</code> would be erroneous in that case, because
the subroutine's implicit <code>$_</code> declaration wouldn't happen till
the opening curly, and instead of getting <code>$OUTER::_</code>, the user would
unexpectedly be getting <code>$OUTER::OUTER::_</code>, as it were.  So instead, we'll
say that the implicit introduction of the new sub's <code>$_</code> variable
<i>always</i> happens after the <code>&lt;subintro&gt;</code> and before the <code>&lt;signature&gt;</code>,
so any use of <code>$_</code> as a default in a signature or
as an argument to a property can only refer to the subroutine's own
topic, if any.  To refer to any external <code>$_</code> you must say either
<code>$CALLER::_</code> or <code>$OUTER::_</code>.  This approach seems much cleaner.</p>
<a name='RFC 160: Function-call named parameters (with compiler optimizations)'></a><h4>RFC 160: Function-call named parameters (with compiler
optimizations)</h4>
<p>For efficiency, we have to be able to hoist the semantics from the
signature into the calling module when that's practical, and that
has to happen at compile time.  That means the information has to be
in the signature, not embedded in a <code>fields()</code> function within the
body of the subroutine.  In fact, my biggest complaint about
this RFC is that it arbitrarily separates the prototype characters,
the parameter names, and the variable names.  That's a recipe for
things getting out of sync.</p>
<p>Basically, this RFC has a lot of the right ideas, but just doesn't
go far enough in the signature direction, based on the (at the
time) laudable notion that we were interested in keeping Perl 6 as
close to Perl 5 as possible.  Which turned out not to be <i>quite</i>
the case. <code>:-)</code> Our new signatures look more hardwired than the
attribute syntax proposed here, but it's all still very hookable
underneath via the sub and parameter traits.  And everything is
together that should be together.</p>
<p>Although the signature is really just a trait underneath, I thought it
important to have special syntax for it, just as there's special syntax
for the body of the function.  Signatures are very special traits, and
people like special things to look special.  It's just more of those
darn psychological reasons that keep popping up in the design of Perl.</p>
<p>Still and all, the current design is optimized for many of the
same sensitivities described in this RFC.</p>
<a name='RFC 128: Subroutines: Extend subroutine contexts to include name parameters and lazy arguments'></a><h4>RFC 128: Subroutines: Extend subroutine contexts to include
name parameters and lazy arguments</h4>
<p>This RFC also has lots of good ideas, but tends to stay a little
too close to Perl 5 in various areas where I've decided to swap
the defaults around.  For instance, marking reference parameters in
prototypes rather than slurpy parameters in signatures, identifying
lazy parameters rather than flattening, and defaulting to <code>rw</code>
(autovivifying lvalue args) rather than <code>constant</code> (rvalue args).</p>
<p>Context classes are handled by the automatic coercion to references
within scalar context, and by type junctions.</p>
<p>Again, I don't buy into two-pass, fill-in-the-blanks argument
processing.</p>
<p>Placeholders are now just for argument declaration, and imply
no currying.  Currying on the other hand is done with an explicit
<code>.assuming</code> method, which requires named args that will be bound to
the corresponding named parameters in the function being curried.</p>
<p>Or should I say functions?  When module and class writers write
systems of subroutines or methods, they usually go to great pains
to make sure all the parameter names are consistent.  Why not take
advantage of that?</p>
<p>So currying might even be extended to classes or modules, where all
methods or subs with a given argument name are curried simultaneously:</p>
<pre>    my module MyIO ::= (use IO::Module).assuming(ioflags =&gt; &quot;:crlf&quot;);
    my class UltAnswer ::= (use Answer a,b,c).assuming(answer =&gt; 42);</pre>
<p>If you curry a class's invocant, it would turn the class into a module instead
of another class, since there are no longer any methods if there are no invocants:</p>
<pre>    my module UltAnswer ::=
        (use Answer a,b,c).assuming(self =&gt; new Answer: 42);</pre>
<p>Or something like that.  If you think this implies that there are
class and module objects that can be sufficiently introspected to do
this sort of chicanery, you'd be right.  On the other hand, given
that we'll have module name aliasing anyway to support running multiple
versions of the same module, why not support multiple curried versions
without explicit renaming of the module:</p>
<pre>    (use IO::Module).assuming(ioflags =&gt; &quot;:crlf&quot;);</pre>
<p>Then for the rest of this scope, IO::Module really points to your
aliased idea of IO::Module, without explicitly binding it to a
different name.  Well, that's for Apocalypse 11, really...</p>
<p>One suggestion from this RFC I've taken to heart, which is to banish
the term &quot;prototype&quot;.  You'll note we call them signatures now.
(You may still call Perl 5's prototypes &quot;prototypes&quot;, of course,
because Perl 5's prototypes really <i>were</i> a prototype of signatures.)</p>
<a name='RFC 344: Elements of @_ should be read-only by default'></a><h4>RFC 344: Elements of <code>@_</code> should be read-only by default</h4>
<p>I admit it, I waffled on this one.  Up until the last moment, I was
going to reject it, because I wanted <code>@_</code> to work exactly like it
does in Perl 5 in subs without a signature.  It seemed like a nice
sop towards backward compatibility.</p>
<p>But when I started writing about why I was rejecting it, I started
thinking about whether a sig-less sub is merely a throwback to Perl 5,
or whether we'll see it continue as a viable Perl 6 syntax.  And if
the latter, perhaps it should be designed to work right rather than
merely to work the same.  The vast majority of subroutines in Perl
5 refrain from modifying their arguments via <code>@_</code>, and it somehow
seems wrong to punish such good deeds.</p>
<p>So I changed my mind, and the default signature on a sub without
a signature is simply <code>(*@_)</code>, meaning that <code>@_</code> is considered an
array of constants by default.  This will probably have good effects
on performance, in general.  If you really want to write through
the <code>@_</code> parameter back into the actual arguments, you'll have to
declare an explicit signature of <code>(*@_ is rw)</code>.</p>
<p>The Perl5-to-Perl6 translator will therefore need to translate:</p>
<pre>    sub {...}</pre>
<p>to:</p>
<pre>    sub (*@_ is rw) {...}</pre>
<p>unless it can be determined that elements of <code>@_</code> are not modified
within the sub.  (It's okay to shift a constant <code>@_</code> though, since
that doesn't change the elements passed to the call; remember that
for slurpy arrays the implied &quot;<code>is constant</code>&quot; or explicit &quot;<code>is rw</code>&quot;
distributes to the individual elements.)</p>
<a name='RFC 194: Standardise Function Pre- and Post-Handling'></a><h4>RFC 194: Standardise Function Pre- and Post-Handling</h4>
<p>Yes, this needs to be standardized, but we'll be generalizing to the
notion of wrappers, which can automatically keep their pre and post
routines in sync, and, more importantly, keep a single lexical scope
across the related pre and post processing.  A wrapper is installed
with the <code>.wrap</code> method, which can have optional parameters to tell it
how to wrap, and which can return an identifier by which the particular
wrapper can be named when unwrapping or otherwise rearranging the
wrappings.  A wrapper automatically knows what function it's wrapped
around, and invoking the <code>call</code> builtin automatically invokes the
next level routine, whether that's the actual routine or another layer
of wrapper.  That does matter, because with that implicit knowledge
<code>call</code> doesn't need to be given the name of the routine to invoke.</p>
<ul>
<li><a name=''></a></li>
<p><i>The implementation is dependent on what happens to typeglobs in Perl
6, how does one inspect and modify the moral equivalent of the symbol
table?</i></p>
</ul>
<p>This is not really a problem, since we've merely split the typeglob up
into separate entries.</p>
<ul>
<li><a name=''></a></li>
<p><i>Also: what will become of prototypes?  Will it become possible
to declare return types of functions?</i></p>
</ul>
<p>Yes.  Note that if you do introspection on a sub ref, by default you're
going to get the signature and return type of the actual routine,
not of any wrappers.  There needs to be some method for introspecting
the wrappers as well, but it's not the default.</p>
<ul>
<li><a name=''></a></li>
<p><i>As pointed out in [JP:HWS] certain intricacies are involved: what are
the semantic of caller()?  Should it see the prehooks?  If yes, how?</i></p>
</ul>
<p>It seems to me that sometimes you want to see the wrappers, and
sometimes you don't.  I think <code>caller</code> needs some kind of argument that
says which levels to recognize and which levels to ignore.  It's not
necessarily a simple priority either.  One invocation may want to find
the innermost enclosing loop, while another might want the innermost
enclosing <code>try</code> block.  A general matching term will be supplied on
such calls, defaulting to ignore the wrappers.</p>
<ul>
<li><a name=''></a></li>
<p><i>How does this relate to the proposed generalized want() [DC:RFC21]?</i></p>
</ul>
<p>The <code>want()</code> function can be viewed as based on <code>caller()</code>, but
with a different interface to the information available at the the
particular call level.</p>
<p>I worry that generalized wrappers will make it impossible to compile
fast subroutine calls, if we always have to allow for run-time
insertion of handlers.  Of course, that's no slower than Perl 5, but
we'd like to do better than Perl 5.  Perhaps we can have the default
be to have wrappable subs, and then turn that off with specific
declarations for speed, such as &quot;<code>is inline</code>&quot;.</p>
<a name='RFC 271: Subroutines : Pre- and post- handlers for subroutines'></a><h4>RFC 271: Subroutines : Pre- and post- handlers for subroutines</h4>
<p>I find it odd to propose using <code>PRE</code> for something with side effects
like flock.  Of course, this RFC was written before <code>FIRST</code> blocks
existed...</p>
<p>[Update: That is, before <code>ENTER</code> blocks existed.]</p>
<p>On the other hand, it's possible that a system of <code>PRE</code> and <code>POST</code>
blocks would need to keep &quot;dossiers&quot; of its own internal state
independent of the &quot;real&quot; data.  So I'm not exactly sure what the
effective difference is between <code>PRE</code> and <code>FIRST</code>.  But we can
always put a <code>PRE</code> into a lexical wrapper if we need to keep info
around till the <code>POST</code>.  So we can keep <code>PRE</code> and <code>POST</code> with the
semantics of simply returning boolean expressions, while <code>FIRST</code>
and <code>LAST</code> are evaluated primarily for side effects.</p>
<p>You might think that you wouldn't need a signature on any pre or post
handler, since it's gonna be the same as the primary.  However, we
have to worry about multimethods of the same name, if the handlers
are defined outside of the subroutine. Again, embedding PRE and
POST blocks either in the routine itself or inside a wrapper around
the routine should handle that.  (And turning the problem into
one of being able to generate a reference to a multimethod with
a particular signature, in essence, doing method dispatch without
actually dispatching at the end.)</p>
<p>[Update: Such an individual multimethod is named with the argument
types in a siglet postfix: <code>&amp;foo:(Bar,Baz)</code>.</p>
<p>My gut feeling is that <code>$_[-1]</code> is a bad place to keep the return
value.  With the <code>call</code> interface we're proposing, you just harvest
the return value of <code>call</code> if you're interested in the return value.
Or perhaps this is a good place for a return signature to actually
have formal variables bound to the return values.</p>
<p>Also, defining pre and post conditions in terms of exceptions is
probably a mistake.  If they're just boolean expressions, they can
be ANDed and ORed together more easily in the approved DBC fashion.</p>
<p>We haven't specified a declarative form of wrapper, merely a <code>.wrap</code>
method that you can call at run time.  However, as with most of Perl,
anything you can do at run time, you can also do at compile time, so
it'd be fairly trivial to come up with a syntax that used a <code>wrap</code>
keyword in place of a <code>sub</code>:</p>
<pre>    wrap split(Regex ?$re, ?$src = $CALLER::_, ?$limit = Inf) {
	print &quot;Entering split\n&quot;;
	call;
	print &quot;Leaving split\n&quot;;
    }</pre>
<p>I keep mistyping &quot;wrap&quot; as &quot;warp&quot;.  I suppose that's not so far off,
actually...</p>
<a name='RFC 21: Subroutines: Replace wantarray with a generic want function'></a><h4>RFC 21: Subroutines: Replace <code>wantarray</code> with a generic
<code>want</code> function</h4>
<p>Overall, I like it, except that it's reinventing several wheels.
It seems that this has evolved into a powerful method for each sub to
do its own overloading based on return type.  How does this play with
a more declarative approach to return types?  I dunno.  For now we're
assuming multmethod dispatch only pays attention to argument types.
We might get rid of a lot of calls to <code>want</code> if we could dispatch
on return type as well.  Perhaps we could do primary dispatch on
the arguments and then do tie-breaking on return type when more
then one multimethod has the same parameter profile.</p>
<p>I also worry a bit that we're assuming an interpreter here that
<i>can</i> keep track of all the context information in a way suitable
for searching by the called subroutine.  When running on top of a
JVM or CLR, this info might not be convenient to provide, and I'd
hate to have to keep a descriptor of every call, or do some kind of
double dispatch, just because the called routine <i>might</i> want to
use <code>want()</code>, or might want to call another routine that might want
to use <code>want</code>, or so on.  Maybe the situation is not that bad.</p>
<p>I sometimes wonder if <code>want</code> should be a method on the context object:</p>
<pre>    given caller.want {...}</pre>
<p>or perhaps the two could be coalesced into a single call:</p>
<pre>    given context { ... }</pre>
<p>But for the moment let's assume for readability that there's a <code>want</code>
function distinct from <code>caller</code>, though with a similar signature:</p>
<pre>    multi *want (?$where = &amp;CALLER::_, Int +$skip = 0, Str +$label)
	returns WantContext {...}</pre>
<p>As with <code>caller</code>, calling <code>want</code> with no arguments looks for
the context of the currently executing subroutine or method.
Like <code>return</code>, it specifically ignores bare blocks and routines
interpreting bare blocks, and finds the context for the lexically
enclosing explicit sub or method declaration, named by <code>&amp;_</code>.</p>
<p>You'll note that unlike in the proposal, we don't pass a list to
<code>want</code>, so we don't support the implicit <code>&amp;&amp;</code> that is proposed for
the arguments to <code>want</code>.  But that's one of the re-invented wheels,
anyway, so I'm not too concerned about that.  What we really want is
a <code>want</code> that works well with smart matching and switch statements.</p>
<a name='RFC 23: Higher order functions'></a><h4>RFC 23: Higher order functions</h4>
<p>In general, this RFC proposes some interesting semantic sugar,
but the rules are too complicated.  There's really no need for
special numbered placeholders.  And the special <code>^_</code> placeholder is
too confusing.  Plus we really need regular sigils on our placeholder
variables so we can distinguish <code>$^x</code> from <code>@^x</code> from <code>%^x</code>.</p>
<p>But the main issue is that the RFC is confusing two separate concepts
(though that can be blamed on the languages this idea was borrowed
from).  Anyway, it turns out we'll have an explicit pre-binding method
called <code>.assuming</code> for actual currying.</p>
<p>We'll make the self-declaring parameters a separate concept, called
placeholder variables.  They don't curry.  Some of the examples of
placeholders in the RFC are actually replaced by topics and junctions
in our smart matching mode, but there are still lots of great uses
for placeholder variables.</p>
<a name='RFC 176: subroutine / generic entity documentation'></a><h4>RFC 176: subroutine / generic entity documentation</h4>
<p>This would be trivial to do with declared traits and here docs.
But it might be better to use a POD directive that is accessible to
the program.  An entity might even have implicit traits that bind
to nearby chunks of the right sort.  Maybe we could get Don Knuth
to come up with something literate...</p>
<a name='RFC 298: Make subroutines' prototypes accessible from Perl'></a><h4>RFC 298: Make subroutines' prototypes accessible from Perl</h4>
<p>While I'm all in favor of a sub's signature being available for
inspection, this RFC goes beyond that to make indirection in the
signature the norm.  This seems to be a solution in search of a
problem.  I'm not sure the confusion of the indirection is worth the
ability to factor out common parameter lists.  Certainly parameter
lists must have introspection, but using it to <i>set</i> the prototype
seems potentially confusing.  That being said, the signatures are
just traits, so this may be one of those things that is permitted,
but not advised, like shooting your horse in the middle of the desert,
or chewing out your SO for burning dinner.  Implicit declaration of
lexically scoped variables will undoubtedly be considered harmful by
somebody someday.  [Damian says, &quot;Me. Today.&quot;]</p>
<a name='RFC 334: Perl should allow specially attributed subs to be called as C functions'></a><h4>RFC 334: Perl should allow specially attributed subs to be
called as C functions</h4>
<p>Fine, Dan, you implement it.  ;-)</p>
<p>Did I claim I ignore the names of RFC authors?  Hmm.</p>
<p>The syntax for the suggested:</p>
<pre>    sub foo : C_visible(&quot;i&quot;, &quot;iii&quot;) {#sub body}</pre>
<p>is probably a bit more verbose in real life:</p>
<pre>    my int sub foo (int $a, int $b, int $c)
	 is callable(&quot;C&quot;,&quot;Python&quot;,&quot;COBOL&quot;) { ... }</pre>
<p>If we can't figure out the &quot;i&quot; and &quot;iii&quot; bits from introspection of
the <code>signature</code> and <code>returns</code> traits, we haven't done introspection
right.  And if we're gonna have an optional type system, I can't think
of a better place to use it than for interfaces to optional languages.</p>
<a name='Acknowledgements'></a><h2>Acknowledgements</h2>
<p>This work was made possible by a grant from the Perl Foundation.
I would like to thank everyone who made this dissertation possible by
their generous support.  So, I will...</p>
<p>Thank you all very, very, very, very much!!!</p>
<p>I should also point out that I would have been stuck forever on some
of these design issues without the repeated prodding (as in cattle)
of the Perl 6 design team.  So I would also like to publicly thank
Allison, chromatic, Damian, Dan, Hugo, Jarkko, Gnat, and Steve.
Thanks, you guys!  Many of the places we said &quot;I&quot; above, I should
have said &quot;we&quot;.</p>
<p>I'd like to publicly thank O'Reilly &amp; Associates for facilitating
the design process in many ways.</p>
<p>I would also like to thank my wife Gloria, but not publicly.</p>
<a name='Future Plans'></a><h2>Future Plans</h2>
<p>From here on out, the Apocalypses are probably going to be coming out
in priority order rather than sequential order.  The next major one
will probably be Apocalypse 12, Objects, though it may take a while
since (like a lot of people in Silicon Valley) I'm in negative cash
flow at the moment, and need to figure out how to feed my family.
But we'll get it done eventually.  Some Apocalypses might be written
by other people, and some of them hardly need to be written at all.
In fact, let's write Apocalypse 7 right now...</p>
<a name='Apocalypse 7: Formats'></a><h1>Apocalypse 7: Formats</h1>
<p>Gone from the core.  See Damian.</p>
<a name='Appendix A: Rationale for pipe operators'></a><h1>Appendix A: Rationale for pipe operators</h1>
<p>As we pointed out in the text, the named form of passing a list has
the disadvantage that you have to know what the formal parameter's
name is.  We could get around that by saying that a null name maps
to the slurp array.  In other words, we could define a <code>=&gt;</code>
unary operator that creates a null key:</p>
<pre>    stuff(@foo, =&gt;(1,2,3))</pre>
<p>We can at least lose the outer parens in this case:</p>
<pre>    stuff @foo, =&gt;(1,2,3)</pre>
<p>But darn it, we can't get rid of those pesky inner parens because of
the precedence of <code>=&gt;</code> with respect to comma.  So perhaps it's
time for a new operator with looser precedence than comma:</p>
<pre>    stuff @foo *: 1,2,3		# * to match * zone marker
    stuff @foo +* 1,2,3		# put the * on the list side
    stuff @foo *=&gt; 1,2,3	# or combine with =&gt; above
    stuff @foo ==&gt; 1,2,3	# maybe just lengthen =&gt;
    stuff @foo &lt;== 1,2,3	# except the dataflow is to the left
    stuff @foo with 1,2,3	# could use a word</pre>
<p>Whichever one we pick, it'd still probably want to construct a special
pair internally, because we have to be able to use it indirectly:</p>
<pre>    @args = (\@foo, '*@' =&gt; (1,2,3));
    stuff *@args;</pre>
<p>[Update: Instead of a &quot;special pair&quot;, we now have Capture objects.]</p>
<p>But if we're going to have a special operator to switch explicitly to
the list part, it really needs to earn its keep, and do more work.
A special operator could also force scalar context on the left and
list context on the right.  So with implied scalar context we could
omit the backslash above:</p>
<pre>    @args = (@foo with 1,2,3);
    stuff *@args;</pre>
<p>That's all well and good, and some language designers would stop
right there, if not sooner.  But if we think about this in relation
to cascaded list operators, we'll see a different pattern emerging.
Here's a left-to-right variant on the Schwartzian Transform:</p>
<pre>    my @x := map {...} @input;
    my @y := sort {...} with @x;
    my @z := map {...} with @y;</pre>
<p>When we think of data flowing left-to-right, it's more like a pipe
operator from a shell, except that we're naming our pipes <code>@x</code>
and <code>@y</code>.  But it'd be nice not to have to name the temporary
array values.  If we do have a pipe operator in Perl, it's not going
to be <code>|</code>, for two reasons.  First, <code>|</code> is taken for junctions.
Second, piping is a big, low-precedence operation, and I want a big
fat operator that will show up to the eye.  Of our candidate list
above, I think the big, fat arrows really stand out, and look like
directed pipes.  So assuming we have the <code>==&gt;</code> operator to go
with the <code>&lt;==</code>, we could write our ST like this:</p>
<pre>    @input     ==&gt;
    map {...}  ==&gt;
    sort {...} ==&gt;
    map {...}  ==&gt;
    push my @z;</pre>
<p>That argues that the scalar-to-list transition operator should be <code>&lt;==</code>:</p>
<pre>    my @x := map {...} @input;
    my @y := sort {...} &lt;== @x;
    my @z := map {...} &lt;== @y;</pre>
<p>And that means this should maybe dwim:</p>
<pre>    @args = (@foo &lt;== 1,2,3);
    stuff *@args;</pre>
<p>Hmm.</p>
<p>That does imply that <code>&lt;==</code> is (at least in this case) a data
composition operator, unlike the <code>==&gt;</code> operator which merely sends
the output of one function to the next.  Maybe that's not a problem.
But people might see:</p>
<pre>    @x &lt;== 1,2,3</pre>
<p>and expect it does assignment when it in fact doesn't.  Internally it
would really do something more like appending a named argument:</p>
<pre>    @x, '*@' =&gt; (1,2,3)</pre>
<p>or however we decide to mark the beginning of the &quot;real&quot; list within
a larger list.</p>
<p>But I do rather like the looks of:</p>
<pre>    push @foo &lt;== 1,2,3;</pre>
<p>not to mention the symmetrical:</p>
<pre>    1,2,3 ==&gt;
    push @foo;</pre>
<p>Note however that the pointy end of <code>==&gt;</code> <i>must</i> be bound to a
function that takes a list.  You can't say:</p>
<pre>    1,2,3 ==&gt;
    my @foo;</pre>
<p>because you can't say:</p>
<pre>    my @foo &lt;== 1,2,3;</pre>
<p>Or rather, you can, if we allow:</p>
<pre>    (@foo &lt;== 1,2,3)</pre>
<p>but it would mean the Wrong Thing.  Ouch.  So maybe that should not
be legal.  The asymmetry was bugging me anyway.</p>
<p>So let's say that <code>&lt;==</code> and <code>==&gt;</code> must always be bound on
their pointy end to a slurpy function, and if you want to build an
indirect argument list, you have to use some kind of explicit list
function such as <code>args</code>:</p>
<pre>    @args = args @foo &lt;== 1,2,3;
    stuff *@args;</pre>
<p>The <code>args</code> function would really be a no-op, much like other context
enforcers such as <code>scalar</code> and <code>list</code>.  In fact, I'd be tempted to
just use <code>list</code> like this:</p>
<pre>    @args = list @foo &lt;== 1,2,3;</pre>
<p>But unless we can get people to see <code>&lt;==</code> as a strange kind of
comma, that will likely be misread as:</p>
<pre>    @args = list(@foo) &lt;== 1,2,3;</pre>
<p>when it's really this:</p>
<pre>    @args = list(@foo &lt;== 1,2,3);</pre>
<p>On the other hand, using <code>list</code> would cut out the need for yet another
built-in, for which there is much to be said...  I'd say, let's go
with <code>list</code> on the assumption that people <i>will</i> learn to read <code>&lt;==</code>
as a pipe comma.  If someone wants to use <code>args</code> for clarity,
they can always just alias <code>list</code>:</p>
<pre>    my &amp;args ::= &amp;*list;</pre>
<p>More likely, they'll just use the parenthesized form:</p>
<pre>    @args = list(@foo &lt;== 1,2,3);</pre>
<p>I suppose there could also be a prefix unary form, in case they want
to use it without scalar arguments:</p>
<pre>    @args = list(&lt;== 1,2,3);</pre>
<p>or in case they want to put a comma after the scalar arguments:</p>
<pre>    @args = list(@foo, &lt;== 1,2,3);</pre>
<p>In fact, it could be argued that we should <i>only</i> have the unary form,
since in this:</p>
<pre>    stan @array, ollie &lt;== 1,2,3</pre>
<p>it's visually ambiguous whether the pointy pipe belongs to <code>stan</code> or
<code>ollie</code>.  It could be ambiguous to the compiler as well.  With a unary
operator, it unambiguously belongs to <code>ollie</code>.  You'd have to say:</p>
<pre>    stan @array, ollie, &lt;== 1,2,3</pre>
<p>to make it belong to <code>stan</code>.  And yet, it'd be really strange for a
unary <code>&lt;==</code> to force the arguments to its left into scalar context
if the operator doesn't govern those arguments syntactically.  And I
still think I want <code>&lt;==</code> to do that.  And it's probably better to
disambiguate with parentheses anyway.  So we keep it a binary operator.
There's no unary variant, either prefix or postfix.  You can always say:</p>
<pre>    list( () &lt;== 1,2,3 )
    list( @foo &lt;== () )</pre>
<p>Similarly, <code>==&gt;</code> is also always a binary operator.  As the
reverse of <code>&lt;==</code>, it forces its left side into list context,
and it also forces all the arguments of the list operator on the
right into scalar context.  Just as:</p>
<pre>    mumble @foo &lt;== @bar</pre>
<p>tells you that <code>@foo</code> is in scalar context and <code>@bar</code> is in list
context regardless of the signature of mumble, so too:</p>
<pre>    @bar ==&gt;
    mumble @foo</pre>
<p>tells you exactly the same thing.  This is particularly useful when you
have a method with an unknown signature that you have to dispatch on:</p>
<pre>    @bar ==&gt;
    $objects[$x].mumble(@foo)</pre>
<p>The <code>==&gt;</code> unambiguously indicates that all the other arguments to
<code>mumble</code> are in scalar context.  It also allows <code>mumble</code>'s signature
to check to see if the number of scalar arguments is within the correct
range, counting only required and optional parameters, since we don't
have to allow for extra arguments to slop into the slurp array.</p>
<p>If we do want extra list arguments, we could conceivably allow both
kinds of pipe at once:</p>
<pre>    @bar ==&gt;
    $objects[$x].mumble(@foo &lt;== 1,2,3)</pre>
<p>If we did that, it could be equivalent to either:</p>
<pre>    $objects[$x].mumble(@foo &lt;== 1,2,3,@bar)</pre>
<p>or:</p>
<pre>    $objects[$x].mumble(@foo &lt;== @bar,1,2,3)</pre>
<p>Since I can argue it both ways, we'll have to disallow it
entirely. <code>:-)</code></p>
<p>Seriously, the conservative thing to do is to disallow it until we
know what we want it to mean, if anything.</p>
<p>On the perl6-language list, an operator was discussed that would do
argument rearrangement, but this is a little different in that it is
constrained (by default) to operate only with the slurpy list part
of the input to a function.  This is as it should be, if you think
about it.  When you pipe things around in Unix, you don't expect
the command line switches to come in via the pipe, but from the
command line.  The scalar arguments of a list operator function as
the command line, and the list argument functions as the pipe.</p>
<p>That being said, if you want to pull the scalar arguments from the
front of the pipe, we already have a mechanism for that:</p>
<pre>    @args = list(@foo &lt;== 1,2,3);
    stuff *@args;</pre>
<p>By extension, we also have this:</p>
<pre>    list(@foo &lt;== 1,2,3) ==&gt;
      stuff *();</pre>
<p>So there's no need for a special syntax to put the invocant after
all the arguments.  It's just this:</p>
<pre>    list(@foo &lt;== 1,2,3) ==&gt;
     $object.stuff *();</pre>
<p>Possibly the <code>*()</code> could be inferred in some cases, but it may be
better not to if we can't do it consistently.  If <code>stuff</code>'s signature
started with optional positional parameters, we wouldn't know whether
the pipe starts with positional arguments or list elements.  I think
that passing positionals at the front of the pipe is rare enough that
it ought to be specially marked with <code>*()</code>.  Maybe we can reduce it
to a <code>*</code>, like a unary that has an optional argument:</p>
<pre>    list(@foo &lt;== 1,2,3) ==&gt;
     $object.stuff *;</pre>
<p>By the way, you may think that we're being silly calling these pipes,
since we're just passing lists around.  But remember that these can
potentially be lazy lists produced by a generator.  Indeed, a common
idiom might be something like:</p>
<pre>    &lt;$*IN&gt; ==&gt; process() ==&gt; print;</pre>
<p>which arguably reads better than:</p>
<pre>    print process &lt;$*IN&gt;;</pre>
<p>Another possibility is that we extend the argumentless <code>*</code> to mark
where the list goes in constructs that take lists but aren't officially
list operators:</p>
<pre>    1,2,3 ==&gt;
    my @foo = (*)</pre>
<p>But maybe we should just make:</p>
<pre>    1,2,3 ==&gt; my @foo;</pre>
<p>do what people will expect it to.  Since we require the <code>list</code>
operator for the other usage, it's easy enough to recognize that this
is not a list operator, and that we should therefore assign it.
It seems to have a kind of inevitability about it.</p>
<p>Damian: &quot;Certainly, if we don't support it, someone (*ahem*) will
immediately write:</p>
<pre>    multi infix:==&gt; (Lazy $list, @array is rw) { @array = $list }
    multi infix:&lt;== (@array is rw, Lazy $list) { @array = $list }</pre>
<p>&quot;So we might as well make it standard.&quot;</p>
<p>[Update: Nowadays those'd be more like:</p>
<pre>    our multi sub *infix:«==&gt;» (Lazy $list, @array is rw) { @array = $list }
    our multi sub *infix:«&lt;==» (@array is rw, Lazy $list) { @array = $list }</pre>
<p>.]</p>
<p>On the other hand...</p>
<p>I'm suddenly wondering if assignment and binding can change precedence
on the right like list operators do if it's known we're assigning to
a list.   I, despite my credentials as TheLarry, keep finding myself
writing list assignments like this:</p>
<pre>    my @foo := 0..9,'a'..'z';</pre>
<p>Oops.  But what if it wasn't an oops.  What if that parsed like a list
operator, and slurped up all the commas to the right?  Parens would
still be required around a list on the left though.  And it might
break weird things like:</p>
<pre>    (@a = (1,2), @b = (3,4))</pre>
<p>But how often do you do a list assignment inside a list?  On the
other hand, making list assignment a different precedence than scalar
is weird.  But it'd have to be that way if we still wanted:</p>
<pre>    ($a = 1, $b = 2)</pre>
<p>to work as a C programmer expects.  Still, I think I like it.  In particular,
it'd let us write what we mean explicitly:</p>
<pre>    1,2,3 ==&gt;
    my @foo = *;</pre>
<p>So let's go ahead and do that, and then maybe someone (*ahem*) might
just forget to overload the pipe operators on arrays.*</p>
<ul>
<li><a name=''></a></li>
<p>* The words &quot;fat&quot;, &quot;slim&quot;, and &quot;none&quot; come to mind.</p>
</ul>
<a name='Appendix B: How to bind strange arguments to weird parameters'></a><h1>Appendix B: How to bind strange arguments to weird parameters</h1>
<p>It may seem like the declaration syntax has too many options (and
it does), but it's actually saving you a good deal of complexity.
When you say something excruciatingly fancy like this:</p>
<pre>    method x ($me: $req, ?$opt, *%named, *@list, +$namedopt) {...}</pre>
<p>you're actually getting a whole pile of semantics resembling this
pseudocode:</p>
<pre>    method x (*@list) {
	my %named;
	my $argnum = 0;

	# find beginning of named arguments
	while exists @list[$argnum] and @list[$argnum] !~ Pair|Hash {
	    $argnum++;
	    last if $argnum == 3;		# force transition to named or list
	}
	my $posmax = $argnum;

	# pull out named actuals (pairs or hashes)
	while exists @list[$argnum] and @list[$argnum] ~~ Pair|Hash {
	    %named.add(@list[$argnum++].pairs);
	}

	# the invocant comes in like this
	my $_   := $posmax &gt; 0 ?? @list[0] :: delete %named{me}  // die &quot;Not enough args&quot;;
	my $me  := $_;				# only if invocant declared

	# required parameters are bound like this
	my $req := $posmax &gt; 1 ?? @list[1] :: delete %named{req} // die &quot;Not enough args&quot;;

	# optional positional parameters are bound like this
	my $opt := $posmax &gt; 2 ?? @list[2] :: delete %named{opt};

	# optional named parameters are bound like this
	my $namedopt := delete %named{namedopt};

	# trim @list down to just the remaining list
	splice(@list, 0, $argnum, ());

	if defined @list {
	    die &quot;Can't have two lists&quot; if exists %named{'*@'};
	}
	else {
	    @list := delete %named{'*@'} // [];
	}

	...	# Your ad here.
    }</pre>
<p>Only hopefully it runs a lot faster.  Regardless, I know which version
I'd rather write...</p>
<p>Or maintain...</p>
<p>You can get even more semantics than that if we need to process
default values or do run-time type checking.  It also gets hairier if
you have any positional parameters declared as <code>Pair</code> or <code>Hash</code>.
On the other hand, the compiler can probably optimize away lots
of the linkage code in general, particularly when it can compare
the actual arguments against the signature at compile time and, for
instance, turn named arguments into positional arguments internally.
Or prebuild a hash of the named args.  Even if it can't do that, it
could generate specially marked lists that already know where the named
arguments start and stop so we don't have to scan for those boundaries.
This gets easier if the caller marks the list part with <code>&lt;==</code>
or <code>==&gt;</code>.  Though it gets harder again if they use splat to pass
indirect positional arguments.</p>
<p>Note also that we don't necessarily have to build a real <code>%named</code>
slurphash.  The <code>%named</code> hash can just be a proxy for a function
that scans those args known to contain named arguments, whether
pairs or hashes.  In general, although there may be quite a few
optional parameters, most of them aren't set in the average call,
so the brute-force approach of scanning the call list linearly for
each possible parameter may well be faster than trying to build a
real hash (particularly if any or all of named parameters already
come in as a hash).</p>
<p>It might be tricky to make bound named arguments disappear from the
proxy hash, however.  In the code above, you'll note that we actually
delete named arguments from <code>%named</code> as we bind them to positional
parameters.  A proxy hash might have to figure out how to hide &quot;used&quot;
values somehow.  Or maybe we just leave them visible as aliases to
bound parameters.  I don't profess to know which is better.  Could be a
pragma for it...seems the usual cure for festering bogons these days...</p>
<p>In our pseudocode above, we don't ever actually evaluate the
arguments of the entire list, because it could be a generated list
like <code>1..Inf</code>, and flattening that kind of list would chew up just
a <i>wee</i> bit too much memory.  If <code>@list</code> were an ordinary array, its
boolean value would tell us if it will produce any values, but that's
not really what we want.  What we really want to know is whether the
caller specified anything, not whether what they specified is going
to produce any values.  If you say:</p>
<pre>    push @foo, 1..0;</pre>
<p>the range doesn't generate any values, but you shouldn't look anywhere
else for the list either.  That is,</p>
<pre>    1,2,3 ==&gt;
    push @foo, 1..0;</pre>
<p>should probably be an error.  It's equivalent to saying:</p>
<pre>    push @foo, '*@'=&gt;(1,2,3), 1..0;</pre>
<p>or some such.  We try to catch that in our pseudocode above.</p>
<p>[Update: We now allow multiple lists as a kind of multidimensional slice.]</p>
<p>When you bind a lazy list to an array name such as <code>@_</code> or <code>@list</code>,
by default it's going to try to give the appearance that the array is
all there, even if behind the scenes it is having to generate values
for you.  In this case, we don't want to flatten the list, so instead
of trying to access any of the values of the variadic list, we just ask
if it is defined.  In Perl 6, an ordinary array is considered defined
if it either has some flattened arguments in it already, or it has an
associated list generator definition of how to produce more elements.
We can figure this out without changing the state of the array.</p>
<p>Contrast this with the array's boolean value, which is true only if
it is <i>known</i> that there are actual elements in the array.  If an
array has no remaining flattened elements but has a definition for how
to produce more, the boolean evaluation must evaluate the definition
sufficiently to determine whether there will be at least one more value.
In the case of a range object, it can ask the range object without
actually flattening another element, but in the limiting case of a
random generator subroutine, it would have to go ahead and call the
wretched generator to get the next flattened element, so that it
can know to return false if there were no next element.</p>
<p>Note that even the flat view of the array doesn't necessarily flatten
until you actually access the array, in which case it flattens as
much as it needs to in order to produce the value you requested,
and no more.</p>
<p>We need a name for the list of internal generators bound to the array.
Since they're behaving as specifications for the array, we'll get at
them using the predefined <code>.specs</code> method that arrays support.</p>
<p>So, for instance, if you say:</p>
<pre>    my @foo := (0..9,'a'..'z');</pre>
<p>then:</p>
<pre>    @foo.length</pre>
<p>would return <code>36</code>, but:</p>
<pre>    @foo.specs.length</pre>
<p>would return 2, one for each range object.  (That's presuming you
didn't already ask for the length of the array, since in general
asking for the length of an array flattens it completely and blows
away the specs--though perhaps in this case the range specs can
calculate their lengths non-destructively.)</p>
<p>[Update: It's <code>.elems</code>, not <code>.length</code>.]</p>
<p>Anyway, in the absence of such a flattening event, both <code>@foo</code>
and <code>@foo.specs</code> are true.  However, if instead you'd given it a
null range:</p>
<pre>    my @foo := 1..0;</pre>
<p>then <code>@foo.specs</code> would be true at least temporarily, but <code>@foo</code>
would be false, because the flattened list contains no values.</p>
<p>Now here's where it gets interesting.  As you process a flat array
view, the corresponding specs mutate:</p>
<pre>    my @flat = 1..10;
    shift @flat;
    print @flat.specs;   # prints 2..10</pre>
<p>The specs aren't just a queue, but also a stack:</p>
<pre>    my @flat = 1..10;
    pop @flat;
    print @flat.specs;   # prints 1..9</pre>
<p>Note that you can <code>pop</code> an array without committing to flattening the
entire list:</p>
<pre>    my @flat = (1..Inf, 1..10);
    pop @flat;
    print @flat.specs;   # prints 1..Inf, 1..9</pre>
<p>If you pop the array 9 more times, the resulting null spec pops itself
from the specs list, and you get a single spec of <code>1..Inf</code> out of
<code>@flat.specs</code>.  (Continuing to pop <code>@flat</code> returns <code>Inf</code> forever,
of course, with no change to the spec.)</p>
<p>However, if you access the last element using the <i>length</i> of the
array, it may try to flatten, and fail:</p>
<pre>    my @flat = (1..Inf, 1..10);
    $last = @flat[@flat - 1];	# Kaboom!</pre>
<p>Still, we should be able to detect the attempt to flatten an infinite
list and give a better diagnostic than Perl 5's &quot;Out of memory&quot;.
Either that, or someone should just up and figure out how to subscript
arrays using transfinite numbers.</p>
<a name='Appendix C: Hypotheticality and Flight Recorders'></a><h1>Appendix C: Hypotheticality and Flight Recorders</h1>
<p>[This is a portion of a letter I sent to the design team.  This stuff
is still in discussion with the internals folks, so please take this
as informative rather than definitive.  But I just thought you might
like to see how sausage is made.  <code>:-)</code>  --Larry]</p>
<pre>    : Seems like you're going to have to explain the C&lt;TEMP&gt;/C&lt;RESTORE&gt; 
    : relationship in A6, Larry, since C&lt;RESTORE&gt; isn't even mentioned
    : there at present.</pre>
<p>I'd like to explain it primarily by making both of them unnecessary
most of the time.</p>
<pre>    : But maybe after a good nights sleep, eh? ;-)</pre>
<p>Okay, I've had a night's sleep.  Whether it was a good one remains
to be seen.  But here's what I'm after.  Forget implementation for
a moment.  What's the interface that people want, in the abstract?
You were starting to think this way yourself with &quot;<code>suppose {...}</code>&quot;.
So let's do some supposin'.</p>
<p>I'll talk about caller and callee here, but I'm really talking about
the user's abstract view vs. the user's implementation view, so it
applies to variables, lvalue routines, and rvalue routines alike.</p>
<p>On the caller side, people want to be able to make a temporary
assumption or a hypothesis.  There is some scope over which the
hypothesis is stated, and then some scope over which the hypothesis
is assumed.  At the end of that scope, the hypothesis may or may
not be retracted.  (I'm trying not to state this in terms of <code>temp</code>
and <code>let</code>, just to keep our current ideas out of it.)</p>
<p>Historically, the scope of the hypothesis <i>statement</i> is a single
variable/value, because <code>local</code> only knew how to temporize that kind
of thing.  The scope of the hypothesis assumption has always extended
to the end of the current dynamic scope.</p>
<p>In the very abstract view, supposing is a transactional function with
two arguments, the first one of which establishes a scope in which
any state change is labelled as provisional.  The second argument
establishes a scope in which we work out the ramifications of that
supposing, which may include other supposings.  In classical terms,
they're the <i>protasis</i> and <i>apodosis</i>:</p>
<pre>    suppose { &lt;pro&gt; } { &lt;apo&gt; }</pre>
<p>At the end of the second scope we decide whether to succeed or fail.
On failure, we unsuppose everything that was supposed from the
beginning, and upon success, we allow certain new &quot;facts&quot; to leak
out into a larger reality (which may itself be a hypothesis, but
leave that aside for the moment).  It's basically commit/rollback.</p>
<p>It could also be written:</p>
<pre>    suppose &lt;pro&gt; {
	&lt;apo&gt;
    }</pre>
<p>to make it look more like an <code>if</code>.  But up till now we've written it:</p>
<pre>    {
	temp &lt;pro&gt;;
	&lt;apo&gt;
    }</pre>
<p>which actually works out fine as a syntax, since every statement
is in a sense conditional on preceding statements.  If we want to
allow a hypothetical result to leak out, we use &quot;let&quot; instead of
&quot;temp&quot;.  Whatever.  I'm not caring about the syntax yet, just the
abstract interface.</p>
<p>And the abstract interface wants both &lt;pro&gt; and &lt;apo&gt; to be as
general as possible.  We already have a completely general &lt;apo&gt;,
but we've severely restricted the &lt;pro&gt; so far to be (in Perl 5)
a storage location, or in Perl 6 (Seb), anything with a <code>.TEMP</code>
method.  You'd like to be able to turn anything involving state
changes into an &lt;pro&gt;, but we can't.  We can only do it to values
that cooperate.</p>
<p>So the real question is what does cooperation look like from the
&quot;callee&quot; end of things?  What's the best interface for cooperating?
I submit that the best interface for that does not look like
<code>TEMP =&gt; {}</code>, or <code>RESTORE {}</code>.  It looks like nothing at all!</p>
<pre>    sub foo { $x = 1234; }
    $x = 0;
    {
	temp foo();
	print $x;	# prints 1234
    }
    print $x;		# prints 0</pre>
<p>How might this work in practice?  If Perl (as a language) is aware
of when it is making a state change, and if it also aware of when it
is doing so in a hypothetical context (*any* hypothetical context in
the dynamic scope), then Perl (as a language) can save its own record
of that state change, filing it with the proper hypothetical context
management authorities, to be undone (or committed) at the appropriate
moment.</p>
<p>That's fine as long as we're running in Perl.  Where an explicit <code>TEMP</code>
method is useful is in the interface to foreign code or data that
doesn't support dynamically scoped hypotheticality.  If a Proxy is
proxying for a Perl variable or attribute, however, then the <code>STORE</code>
already knows its dynamic context, and handles <code>temp</code> and <code>let</code>
implicitly just as any other Perl code running in hypothetical context
would.</p>
<p>As for a hypothesis within a hypothesis, I think it just means that
when you refrain from <code>UNDO</code>ing the <code>let</code> state changes, you actually
<code>KEEP</code> them into a higher undo list, if there is one.  (In practice,
this may mean there aren't separate <code>LAST</code> and <code>UNDO</code> lists.  Just a <code>LAST</code>
list, in which some entries do a <code>KEEP</code> or <code>UNDO</code> at the last moment.
Otherwise a <code>let</code> within a <code>let</code> has to poke something onto both a
keep list and an undo list.  But maybe it comes out to the same thing.)</p>
<p>(In any event, we do probably need a name for the current innermost
supposition we're in the dynamic scope of.  I have my doubts that <code>$?_</code>
is that name, however.  <code>$0</code> is closer to it.  Can thrash that out later.)</p>
<p>That's all very powerful.  But here's where it borders on disruptive
technology.  I mentioned a while back the talk by Todd A. Proebsting
on Disruptive Language Technologies.  In it he projects which
new disruptive language technologies will take over the world someday.
The one that stuck in my head was the flight data recorder, where
every state change for the last N instructions was recorded for
analysis in case of failure.  Sound familiar?</p>
<p>Taken together with my hypotheticality hypothesis, I think this likely
indicates a two-birds-with-one-stone situation that we must design for.
If state changes are automatically stored in a type-appropriate
manner, we don't necessarily have to generate tons of artificial
closures merely to create artificial lexical variables just so we
have them around later at the right moment.  I don't mind writing
double closures for things like macros, where they're not in hot code.
But <code>let</code> and friends need to be blazing fast if we're ever going to
use Perl for logic programming, or even recursive descent parsing.
And if we want a flight data recorder, it had better not hang on
the outside of the airplane where it'll induce drag.</p>
<p>And that's what I think is wrong with our Sebastopolian formulation
of <code>.TEMP</code>.  Am I making any sense?</p>
<p>Larry</p>
</div>
